APFloat.cpp 115 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886
  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/APSInt.h"
  16. #include "llvm/ADT/FoldingSet.h"
  17. #include "llvm/ADT/Hashing.h"
  18. #include "llvm/ADT/StringExtras.h"
  19. #include "llvm/ADT/StringRef.h"
  20. #include "llvm/Support/ErrorHandling.h"
  21. #include "llvm/Support/MathExtras.h"
  22. #include <cstring>
  23. #include <limits.h>
  24. using namespace llvm;
  25. /// A macro used to combine two fcCategory enums into one key which can be used
  26. /// in a switch statement to classify how the interaction of two APFloat's
  27. /// categories affects an operation.
  28. ///
  29. /// TODO: If clang source code is ever allowed to use constexpr in its own
  30. /// codebase, change this into a static inline function.
  31. #define PackCategoriesIntoKey(_lhs, _rhs) ((_lhs) * 4 + (_rhs))
  32. /* Assumed in hexadecimal significand parsing, and conversion to
  33. hexadecimal strings. */
  34. #define COMPILE_TIME_ASSERT(cond) extern int CTAssert[(cond) ? 1 : -1]
  35. COMPILE_TIME_ASSERT(integerPartWidth % 4 == 0);
  36. namespace llvm {
  37. /* Represents floating point arithmetic semantics. */
  38. struct fltSemantics {
  39. /* The largest E such that 2^E is representable; this matches the
  40. definition of IEEE 754. */
  41. APFloat::ExponentType maxExponent;
  42. /* The smallest E such that 2^E is a normalized number; this
  43. matches the definition of IEEE 754. */
  44. APFloat::ExponentType minExponent;
  45. /* Number of bits in the significand. This includes the integer
  46. bit. */
  47. unsigned int precision;
  48. };
  49. const fltSemantics APFloat::IEEEhalf = { 15, -14, 11 };
  50. const fltSemantics APFloat::IEEEsingle = { 127, -126, 24 };
  51. const fltSemantics APFloat::IEEEdouble = { 1023, -1022, 53 };
  52. const fltSemantics APFloat::IEEEquad = { 16383, -16382, 113 };
  53. const fltSemantics APFloat::x87DoubleExtended = { 16383, -16382, 64 };
  54. const fltSemantics APFloat::Bogus = { 0, 0, 0 };
  55. /* The PowerPC format consists of two doubles. It does not map cleanly
  56. onto the usual format above. It is approximated using twice the
  57. mantissa bits. Note that for exponents near the double minimum,
  58. we no longer can represent the full 106 mantissa bits, so those
  59. will be treated as denormal numbers.
  60. FIXME: While this approximation is equivalent to what GCC uses for
  61. compile-time arithmetic on PPC double-double numbers, it is not able
  62. to represent all possible values held by a PPC double-double number,
  63. for example: (long double) 1.0 + (long double) 0x1p-106
  64. Should this be replaced by a full emulation of PPC double-double? */
  65. const fltSemantics APFloat::PPCDoubleDouble = { 1023, -1022 + 53, 53 + 53 };
  66. /* A tight upper bound on number of parts required to hold the value
  67. pow(5, power) is
  68. power * 815 / (351 * integerPartWidth) + 1
  69. However, whilst the result may require only this many parts,
  70. because we are multiplying two values to get it, the
  71. multiplication may require an extra part with the excess part
  72. being zero (consider the trivial case of 1 * 1, tcFullMultiply
  73. requires two parts to hold the single-part result). So we add an
  74. extra one to guarantee enough space whilst multiplying. */
  75. const unsigned int maxExponent = 16383;
  76. const unsigned int maxPrecision = 113;
  77. const unsigned int maxPowerOfFiveExponent = maxExponent + maxPrecision - 1;
  78. const unsigned int maxPowerOfFiveParts = 2 + ((maxPowerOfFiveExponent * 815)
  79. / (351 * integerPartWidth));
  80. }
  81. /* A bunch of private, handy routines. */
  82. static inline unsigned int
  83. partCountForBits(unsigned int bits)
  84. {
  85. return ((bits) + integerPartWidth - 1) / integerPartWidth;
  86. }
  87. /* Returns 0U-9U. Return values >= 10U are not digits. */
  88. static inline unsigned int
  89. decDigitValue(unsigned int c)
  90. {
  91. return c - '0';
  92. }
  93. /* Return the value of a decimal exponent of the form
  94. [+-]ddddddd.
  95. If the exponent overflows, returns a large exponent with the
  96. appropriate sign. */
  97. static int
  98. readExponent(StringRef::iterator begin, StringRef::iterator end)
  99. {
  100. bool isNegative;
  101. unsigned int absExponent;
  102. const unsigned int overlargeExponent = 24000; /* FIXME. */
  103. StringRef::iterator p = begin;
  104. assert(p != end && "Exponent has no digits");
  105. isNegative = (*p == '-');
  106. if (*p == '-' || *p == '+') {
  107. p++;
  108. assert(p != end && "Exponent has no digits");
  109. }
  110. absExponent = decDigitValue(*p++);
  111. assert(absExponent < 10U && "Invalid character in exponent");
  112. for (; p != end; ++p) {
  113. unsigned int value;
  114. value = decDigitValue(*p);
  115. assert(value < 10U && "Invalid character in exponent");
  116. value += absExponent * 10;
  117. if (absExponent >= overlargeExponent) {
  118. absExponent = overlargeExponent;
  119. p = end; /* outwit assert below */
  120. break;
  121. }
  122. absExponent = value;
  123. }
  124. assert(p == end && "Invalid exponent in exponent");
  125. if (isNegative)
  126. return -(int) absExponent;
  127. else
  128. return (int) absExponent;
  129. }
  130. /* This is ugly and needs cleaning up, but I don't immediately see
  131. how whilst remaining safe. */
  132. static int
  133. totalExponent(StringRef::iterator p, StringRef::iterator end,
  134. int exponentAdjustment)
  135. {
  136. int unsignedExponent;
  137. bool negative, overflow;
  138. int exponent = 0;
  139. assert(p != end && "Exponent has no digits");
  140. negative = *p == '-';
  141. if (*p == '-' || *p == '+') {
  142. p++;
  143. assert(p != end && "Exponent has no digits");
  144. }
  145. unsignedExponent = 0;
  146. overflow = false;
  147. for (; p != end; ++p) {
  148. unsigned int value;
  149. value = decDigitValue(*p);
  150. assert(value < 10U && "Invalid character in exponent");
  151. unsignedExponent = unsignedExponent * 10 + value;
  152. if (unsignedExponent > 32767) {
  153. overflow = true;
  154. break;
  155. }
  156. }
  157. if (exponentAdjustment > 32767 || exponentAdjustment < -32768)
  158. overflow = true;
  159. if (!overflow) {
  160. exponent = unsignedExponent;
  161. if (negative)
  162. exponent = -exponent;
  163. exponent += exponentAdjustment;
  164. if (exponent > 32767 || exponent < -32768)
  165. overflow = true;
  166. }
  167. if (overflow)
  168. exponent = negative ? -32768: 32767;
  169. return exponent;
  170. }
  171. static StringRef::iterator
  172. skipLeadingZeroesAndAnyDot(StringRef::iterator begin, StringRef::iterator end,
  173. StringRef::iterator *dot)
  174. {
  175. StringRef::iterator p = begin;
  176. *dot = end;
  177. while (*p == '0' && p != end)
  178. p++;
  179. if (*p == '.') {
  180. *dot = p++;
  181. assert(end - begin != 1 && "Significand has no digits");
  182. while (*p == '0' && p != end)
  183. p++;
  184. }
  185. return p;
  186. }
  187. /* Given a normal decimal floating point number of the form
  188. dddd.dddd[eE][+-]ddd
  189. where the decimal point and exponent are optional, fill out the
  190. structure D. Exponent is appropriate if the significand is
  191. treated as an integer, and normalizedExponent if the significand
  192. is taken to have the decimal point after a single leading
  193. non-zero digit.
  194. If the value is zero, V->firstSigDigit points to a non-digit, and
  195. the return exponent is zero.
  196. */
  197. struct decimalInfo {
  198. const char *firstSigDigit;
  199. const char *lastSigDigit;
  200. int exponent;
  201. int normalizedExponent;
  202. };
  203. static void
  204. interpretDecimal(StringRef::iterator begin, StringRef::iterator end,
  205. decimalInfo *D)
  206. {
  207. StringRef::iterator dot = end;
  208. StringRef::iterator p = skipLeadingZeroesAndAnyDot (begin, end, &dot);
  209. D->firstSigDigit = p;
  210. D->exponent = 0;
  211. D->normalizedExponent = 0;
  212. for (; p != end; ++p) {
  213. if (*p == '.') {
  214. assert(dot == end && "String contains multiple dots");
  215. dot = p++;
  216. if (p == end)
  217. break;
  218. }
  219. if (decDigitValue(*p) >= 10U)
  220. break;
  221. }
  222. if (p != end) {
  223. assert((*p == 'e' || *p == 'E') && "Invalid character in significand");
  224. assert(p != begin && "Significand has no digits");
  225. assert((dot == end || p - begin != 1) && "Significand has no digits");
  226. /* p points to the first non-digit in the string */
  227. D->exponent = readExponent(p + 1, end);
  228. /* Implied decimal point? */
  229. if (dot == end)
  230. dot = p;
  231. }
  232. /* If number is all zeroes accept any exponent. */
  233. if (p != D->firstSigDigit) {
  234. /* Drop insignificant trailing zeroes. */
  235. if (p != begin) {
  236. do
  237. do
  238. p--;
  239. while (p != begin && *p == '0');
  240. while (p != begin && *p == '.');
  241. }
  242. /* Adjust the exponents for any decimal point. */
  243. D->exponent += static_cast<APFloat::ExponentType>((dot - p) - (dot > p));
  244. D->normalizedExponent = (D->exponent +
  245. static_cast<APFloat::ExponentType>((p - D->firstSigDigit)
  246. - (dot > D->firstSigDigit && dot < p)));
  247. }
  248. D->lastSigDigit = p;
  249. }
  250. /* Return the trailing fraction of a hexadecimal number.
  251. DIGITVALUE is the first hex digit of the fraction, P points to
  252. the next digit. */
  253. static lostFraction
  254. trailingHexadecimalFraction(StringRef::iterator p, StringRef::iterator end,
  255. unsigned int digitValue)
  256. {
  257. unsigned int hexDigit;
  258. /* If the first trailing digit isn't 0 or 8 we can work out the
  259. fraction immediately. */
  260. if (digitValue > 8)
  261. return lfMoreThanHalf;
  262. else if (digitValue < 8 && digitValue > 0)
  263. return lfLessThanHalf;
  264. // Otherwise we need to find the first non-zero digit.
  265. while (p != end && (*p == '0' || *p == '.'))
  266. p++;
  267. assert(p != end && "Invalid trailing hexadecimal fraction!");
  268. hexDigit = hexDigitValue(*p);
  269. /* If we ran off the end it is exactly zero or one-half, otherwise
  270. a little more. */
  271. if (hexDigit == -1U)
  272. return digitValue == 0 ? lfExactlyZero: lfExactlyHalf;
  273. else
  274. return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf;
  275. }
  276. /* Return the fraction lost were a bignum truncated losing the least
  277. significant BITS bits. */
  278. static lostFraction
  279. lostFractionThroughTruncation(const integerPart *parts,
  280. unsigned int partCount,
  281. unsigned int bits)
  282. {
  283. unsigned int lsb;
  284. lsb = APInt::tcLSB(parts, partCount);
  285. /* Note this is guaranteed true if bits == 0, or LSB == -1U. */
  286. if (bits <= lsb)
  287. return lfExactlyZero;
  288. if (bits == lsb + 1)
  289. return lfExactlyHalf;
  290. if (bits <= partCount * integerPartWidth &&
  291. APInt::tcExtractBit(parts, bits - 1))
  292. return lfMoreThanHalf;
  293. return lfLessThanHalf;
  294. }
  295. /* Shift DST right BITS bits noting lost fraction. */
  296. static lostFraction
  297. shiftRight(integerPart *dst, unsigned int parts, unsigned int bits)
  298. {
  299. lostFraction lost_fraction;
  300. lost_fraction = lostFractionThroughTruncation(dst, parts, bits);
  301. APInt::tcShiftRight(dst, parts, bits);
  302. return lost_fraction;
  303. }
  304. /* Combine the effect of two lost fractions. */
  305. static lostFraction
  306. combineLostFractions(lostFraction moreSignificant,
  307. lostFraction lessSignificant)
  308. {
  309. if (lessSignificant != lfExactlyZero) {
  310. if (moreSignificant == lfExactlyZero)
  311. moreSignificant = lfLessThanHalf;
  312. else if (moreSignificant == lfExactlyHalf)
  313. moreSignificant = lfMoreThanHalf;
  314. }
  315. return moreSignificant;
  316. }
  317. /* The error from the true value, in half-ulps, on multiplying two
  318. floating point numbers, which differ from the value they
  319. approximate by at most HUE1 and HUE2 half-ulps, is strictly less
  320. than the returned value.
  321. See "How to Read Floating Point Numbers Accurately" by William D
  322. Clinger. */
  323. static unsigned int
  324. HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
  325. {
  326. assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
  327. if (HUerr1 + HUerr2 == 0)
  328. return inexactMultiply * 2; /* <= inexactMultiply half-ulps. */
  329. else
  330. return inexactMultiply + 2 * (HUerr1 + HUerr2);
  331. }
  332. /* The number of ulps from the boundary (zero, or half if ISNEAREST)
  333. when the least significant BITS are truncated. BITS cannot be
  334. zero. */
  335. static integerPart
  336. ulpsFromBoundary(const integerPart *parts, unsigned int bits, bool isNearest)
  337. {
  338. unsigned int count, partBits;
  339. integerPart part, boundary;
  340. assert(bits != 0);
  341. bits--;
  342. count = bits / integerPartWidth;
  343. partBits = bits % integerPartWidth + 1;
  344. part = parts[count] & (~(integerPart) 0 >> (integerPartWidth - partBits));
  345. if (isNearest)
  346. boundary = (integerPart) 1 << (partBits - 1);
  347. else
  348. boundary = 0;
  349. if (count == 0) {
  350. if (part - boundary <= boundary - part)
  351. return part - boundary;
  352. else
  353. return boundary - part;
  354. }
  355. if (part == boundary) {
  356. while (--count)
  357. if (parts[count])
  358. return ~(integerPart) 0; /* A lot. */
  359. return parts[0];
  360. } else if (part == boundary - 1) {
  361. while (--count)
  362. if (~parts[count])
  363. return ~(integerPart) 0; /* A lot. */
  364. return -parts[0];
  365. }
  366. return ~(integerPart) 0; /* A lot. */
  367. }
  368. /* Place pow(5, power) in DST, and return the number of parts used.
  369. DST must be at least one part larger than size of the answer. */
  370. static unsigned int
  371. powerOf5(integerPart *dst, unsigned int power)
  372. {
  373. static const integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125,
  374. 15625, 78125 };
  375. integerPart pow5s[maxPowerOfFiveParts * 2 + 5];
  376. pow5s[0] = 78125 * 5;
  377. unsigned int partsCount[16] = { 1 };
  378. integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5;
  379. unsigned int result;
  380. assert(power <= maxExponent);
  381. p1 = dst;
  382. p2 = scratch;
  383. *p1 = firstEightPowers[power & 7];
  384. power >>= 3;
  385. result = 1;
  386. pow5 = pow5s;
  387. for (unsigned int n = 0; power; power >>= 1, n++) {
  388. unsigned int pc;
  389. pc = partsCount[n];
  390. /* Calculate pow(5,pow(2,n+3)) if we haven't yet. */
  391. if (pc == 0) {
  392. pc = partsCount[n - 1];
  393. APInt::tcFullMultiply(pow5, pow5 - pc, pow5 - pc, pc, pc);
  394. pc *= 2;
  395. if (pow5[pc - 1] == 0)
  396. pc--;
  397. partsCount[n] = pc;
  398. }
  399. if (power & 1) {
  400. integerPart *tmp;
  401. APInt::tcFullMultiply(p2, p1, pow5, result, pc);
  402. result += pc;
  403. if (p2[result - 1] == 0)
  404. result--;
  405. /* Now result is in p1 with partsCount parts and p2 is scratch
  406. space. */
  407. tmp = p1, p1 = p2, p2 = tmp;
  408. }
  409. pow5 += pc;
  410. }
  411. if (p1 != dst)
  412. APInt::tcAssign(dst, p1, result);
  413. return result;
  414. }
  415. /* Zero at the end to avoid modular arithmetic when adding one; used
  416. when rounding up during hexadecimal output. */
  417. static const char hexDigitsLower[] = "0123456789abcdef0";
  418. static const char hexDigitsUpper[] = "0123456789ABCDEF0";
  419. static const char infinityL[] = "infinity";
  420. static const char infinityU[] = "INFINITY";
  421. static const char NaNL[] = "nan";
  422. static const char NaNU[] = "NAN";
  423. /* Write out an integerPart in hexadecimal, starting with the most
  424. significant nibble. Write out exactly COUNT hexdigits, return
  425. COUNT. */
  426. static unsigned int
  427. partAsHex (char *dst, integerPart part, unsigned int count,
  428. const char *hexDigitChars)
  429. {
  430. unsigned int result = count;
  431. assert(count != 0 && count <= integerPartWidth / 4);
  432. part >>= (integerPartWidth - 4 * count);
  433. while (count--) {
  434. dst[count] = hexDigitChars[part & 0xf];
  435. part >>= 4;
  436. }
  437. return result;
  438. }
  439. /* Write out an unsigned decimal integer. */
  440. static char *
  441. writeUnsignedDecimal (char *dst, unsigned int n)
  442. {
  443. char buff[40], *p;
  444. p = buff;
  445. do
  446. *p++ = '0' + n % 10;
  447. while (n /= 10);
  448. do
  449. *dst++ = *--p;
  450. while (p != buff);
  451. return dst;
  452. }
  453. /* Write out a signed decimal integer. */
  454. static char *
  455. writeSignedDecimal (char *dst, int value)
  456. {
  457. if (value < 0) {
  458. *dst++ = '-';
  459. dst = writeUnsignedDecimal(dst, -(unsigned) value);
  460. } else
  461. dst = writeUnsignedDecimal(dst, value);
  462. return dst;
  463. }
  464. /* Constructors. */
  465. void
  466. APFloat::initialize(const fltSemantics *ourSemantics)
  467. {
  468. unsigned int count;
  469. semantics = ourSemantics;
  470. count = partCount();
  471. if (count > 1)
  472. significand.parts = new integerPart[count];
  473. }
  474. void
  475. APFloat::freeSignificand()
  476. {
  477. if (needsCleanup())
  478. delete [] significand.parts;
  479. }
  480. void
  481. APFloat::assign(const APFloat &rhs)
  482. {
  483. assert(semantics == rhs.semantics);
  484. sign = rhs.sign;
  485. category = rhs.category;
  486. exponent = rhs.exponent;
  487. if (isFiniteNonZero() || category == fcNaN)
  488. copySignificand(rhs);
  489. }
  490. void
  491. APFloat::copySignificand(const APFloat &rhs)
  492. {
  493. assert(isFiniteNonZero() || category == fcNaN);
  494. assert(rhs.partCount() >= partCount());
  495. APInt::tcAssign(significandParts(), rhs.significandParts(),
  496. partCount());
  497. }
  498. /* Make this number a NaN, with an arbitrary but deterministic value
  499. for the significand. If double or longer, this is a signalling NaN,
  500. which may not be ideal. If float, this is QNaN(0). */
  501. void APFloat::makeNaN(bool SNaN, bool Negative, const APInt *fill)
  502. {
  503. category = fcNaN;
  504. sign = Negative;
  505. integerPart *significand = significandParts();
  506. unsigned numParts = partCount();
  507. // Set the significand bits to the fill.
  508. if (!fill || fill->getNumWords() < numParts)
  509. APInt::tcSet(significand, 0, numParts);
  510. if (fill) {
  511. APInt::tcAssign(significand, fill->getRawData(),
  512. std::min(fill->getNumWords(), numParts));
  513. // Zero out the excess bits of the significand.
  514. unsigned bitsToPreserve = semantics->precision - 1;
  515. unsigned part = bitsToPreserve / 64;
  516. bitsToPreserve %= 64;
  517. significand[part] &= ((1ULL << bitsToPreserve) - 1);
  518. for (part++; part != numParts; ++part)
  519. significand[part] = 0;
  520. }
  521. unsigned QNaNBit = semantics->precision - 2;
  522. if (SNaN) {
  523. // We always have to clear the QNaN bit to make it an SNaN.
  524. APInt::tcClearBit(significand, QNaNBit);
  525. // If there are no bits set in the payload, we have to set
  526. // *something* to make it a NaN instead of an infinity;
  527. // conventionally, this is the next bit down from the QNaN bit.
  528. if (APInt::tcIsZero(significand, numParts))
  529. APInt::tcSetBit(significand, QNaNBit - 1);
  530. } else {
  531. // We always have to set the QNaN bit to make it a QNaN.
  532. APInt::tcSetBit(significand, QNaNBit);
  533. }
  534. // For x87 extended precision, we want to make a NaN, not a
  535. // pseudo-NaN. Maybe we should expose the ability to make
  536. // pseudo-NaNs?
  537. if (semantics == &APFloat::x87DoubleExtended)
  538. APInt::tcSetBit(significand, QNaNBit + 1);
  539. }
  540. APFloat APFloat::makeNaN(const fltSemantics &Sem, bool SNaN, bool Negative,
  541. const APInt *fill) {
  542. APFloat value(Sem, uninitialized);
  543. value.makeNaN(SNaN, Negative, fill);
  544. return value;
  545. }
  546. APFloat &
  547. APFloat::operator=(const APFloat &rhs)
  548. {
  549. if (this != &rhs) {
  550. if (semantics != rhs.semantics) {
  551. freeSignificand();
  552. initialize(rhs.semantics);
  553. }
  554. assign(rhs);
  555. }
  556. return *this;
  557. }
  558. bool
  559. APFloat::isDenormal() const {
  560. return isFiniteNonZero() && (exponent == semantics->minExponent) &&
  561. (APInt::tcExtractBit(significandParts(),
  562. semantics->precision - 1) == 0);
  563. }
  564. bool
  565. APFloat::isSmallest() const {
  566. // The smallest number by magnitude in our format will be the smallest
  567. // denormal, i.e. the floating point number with exponent being minimum
  568. // exponent and significand bitwise equal to 1 (i.e. with MSB equal to 0).
  569. return isFiniteNonZero() && exponent == semantics->minExponent &&
  570. significandMSB() == 0;
  571. }
  572. bool APFloat::isSignificandAllOnes() const {
  573. // Test if the significand excluding the integral bit is all ones. This allows
  574. // us to test for binade boundaries.
  575. const integerPart *Parts = significandParts();
  576. const unsigned PartCount = partCount();
  577. for (unsigned i = 0; i < PartCount - 1; i++)
  578. if (~Parts[i])
  579. return false;
  580. // Set the unused high bits to all ones when we compare.
  581. const unsigned NumHighBits =
  582. PartCount*integerPartWidth - semantics->precision + 1;
  583. assert(NumHighBits <= integerPartWidth && "Can not have more high bits to "
  584. "fill than integerPartWidth");
  585. const integerPart HighBitFill =
  586. ~integerPart(0) << (integerPartWidth - NumHighBits);
  587. if (~(Parts[PartCount - 1] | HighBitFill))
  588. return false;
  589. return true;
  590. }
  591. bool APFloat::isSignificandAllZeros() const {
  592. // Test if the significand excluding the integral bit is all zeros. This
  593. // allows us to test for binade boundaries.
  594. const integerPart *Parts = significandParts();
  595. const unsigned PartCount = partCount();
  596. for (unsigned i = 0; i < PartCount - 1; i++)
  597. if (Parts[i])
  598. return false;
  599. const unsigned NumHighBits =
  600. PartCount*integerPartWidth - semantics->precision + 1;
  601. assert(NumHighBits <= integerPartWidth && "Can not have more high bits to "
  602. "clear than integerPartWidth");
  603. const integerPart HighBitMask = ~integerPart(0) >> NumHighBits;
  604. if (Parts[PartCount - 1] & HighBitMask)
  605. return false;
  606. return true;
  607. }
  608. bool
  609. APFloat::isLargest() const {
  610. // The largest number by magnitude in our format will be the floating point
  611. // number with maximum exponent and with significand that is all ones.
  612. return isFiniteNonZero() && exponent == semantics->maxExponent
  613. && isSignificandAllOnes();
  614. }
  615. bool
  616. APFloat::bitwiseIsEqual(const APFloat &rhs) const {
  617. if (this == &rhs)
  618. return true;
  619. if (semantics != rhs.semantics ||
  620. category != rhs.category ||
  621. sign != rhs.sign)
  622. return false;
  623. if (category==fcZero || category==fcInfinity)
  624. return true;
  625. else if (isFiniteNonZero() && exponent!=rhs.exponent)
  626. return false;
  627. else {
  628. int i= partCount();
  629. const integerPart* p=significandParts();
  630. const integerPart* q=rhs.significandParts();
  631. for (; i>0; i--, p++, q++) {
  632. if (*p != *q)
  633. return false;
  634. }
  635. return true;
  636. }
  637. }
  638. APFloat::APFloat(const fltSemantics &ourSemantics, integerPart value) {
  639. initialize(&ourSemantics);
  640. sign = 0;
  641. category = fcNormal;
  642. zeroSignificand();
  643. exponent = ourSemantics.precision - 1;
  644. significandParts()[0] = value;
  645. normalize(rmNearestTiesToEven, lfExactlyZero);
  646. }
  647. APFloat::APFloat(const fltSemantics &ourSemantics) {
  648. initialize(&ourSemantics);
  649. category = fcZero;
  650. sign = false;
  651. }
  652. APFloat::APFloat(const fltSemantics &ourSemantics, uninitializedTag tag) {
  653. // Allocates storage if necessary but does not initialize it.
  654. initialize(&ourSemantics);
  655. }
  656. APFloat::APFloat(const fltSemantics &ourSemantics, StringRef text) {
  657. initialize(&ourSemantics);
  658. convertFromString(text, rmNearestTiesToEven);
  659. }
  660. APFloat::APFloat(const APFloat &rhs) {
  661. initialize(rhs.semantics);
  662. assign(rhs);
  663. }
  664. APFloat::~APFloat()
  665. {
  666. freeSignificand();
  667. }
  668. // Profile - This method 'profiles' an APFloat for use with FoldingSet.
  669. void APFloat::Profile(FoldingSetNodeID& ID) const {
  670. ID.Add(bitcastToAPInt());
  671. }
  672. unsigned int
  673. APFloat::partCount() const
  674. {
  675. return partCountForBits(semantics->precision + 1);
  676. }
  677. unsigned int
  678. APFloat::semanticsPrecision(const fltSemantics &semantics)
  679. {
  680. return semantics.precision;
  681. }
  682. const integerPart *
  683. APFloat::significandParts() const
  684. {
  685. return const_cast<APFloat *>(this)->significandParts();
  686. }
  687. integerPart *
  688. APFloat::significandParts()
  689. {
  690. if (partCount() > 1)
  691. return significand.parts;
  692. else
  693. return &significand.part;
  694. }
  695. void
  696. APFloat::zeroSignificand()
  697. {
  698. APInt::tcSet(significandParts(), 0, partCount());
  699. }
  700. /* Increment an fcNormal floating point number's significand. */
  701. void
  702. APFloat::incrementSignificand()
  703. {
  704. integerPart carry;
  705. carry = APInt::tcIncrement(significandParts(), partCount());
  706. /* Our callers should never cause us to overflow. */
  707. assert(carry == 0);
  708. (void)carry;
  709. }
  710. /* Add the significand of the RHS. Returns the carry flag. */
  711. integerPart
  712. APFloat::addSignificand(const APFloat &rhs)
  713. {
  714. integerPart *parts;
  715. parts = significandParts();
  716. assert(semantics == rhs.semantics);
  717. assert(exponent == rhs.exponent);
  718. return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
  719. }
  720. /* Subtract the significand of the RHS with a borrow flag. Returns
  721. the borrow flag. */
  722. integerPart
  723. APFloat::subtractSignificand(const APFloat &rhs, integerPart borrow)
  724. {
  725. integerPart *parts;
  726. parts = significandParts();
  727. assert(semantics == rhs.semantics);
  728. assert(exponent == rhs.exponent);
  729. return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
  730. partCount());
  731. }
  732. /* Multiply the significand of the RHS. If ADDEND is non-NULL, add it
  733. on to the full-precision result of the multiplication. Returns the
  734. lost fraction. */
  735. lostFraction
  736. APFloat::multiplySignificand(const APFloat &rhs, const APFloat *addend)
  737. {
  738. unsigned int omsb; // One, not zero, based MSB.
  739. unsigned int partsCount, newPartsCount, precision;
  740. integerPart *lhsSignificand;
  741. integerPart scratch[4];
  742. integerPart *fullSignificand;
  743. lostFraction lost_fraction;
  744. bool ignored;
  745. assert(semantics == rhs.semantics);
  746. precision = semantics->precision;
  747. newPartsCount = partCountForBits(precision * 2);
  748. if (newPartsCount > 4)
  749. fullSignificand = new integerPart[newPartsCount];
  750. else
  751. fullSignificand = scratch;
  752. lhsSignificand = significandParts();
  753. partsCount = partCount();
  754. APInt::tcFullMultiply(fullSignificand, lhsSignificand,
  755. rhs.significandParts(), partsCount, partsCount);
  756. lost_fraction = lfExactlyZero;
  757. omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
  758. exponent += rhs.exponent;
  759. // Assume the operands involved in the multiplication are single-precision
  760. // FP, and the two multiplicants are:
  761. // *this = a23 . a22 ... a0 * 2^e1
  762. // rhs = b23 . b22 ... b0 * 2^e2
  763. // the result of multiplication is:
  764. // *this = c47 c46 . c45 ... c0 * 2^(e1+e2)
  765. // Note that there are two significant bits at the left-hand side of the
  766. // radix point. Move the radix point toward left by one bit, and adjust
  767. // exponent accordingly.
  768. exponent += 1;
  769. if (addend) {
  770. // The intermediate result of the multiplication has "2 * precision"
  771. // signicant bit; adjust the addend to be consistent with mul result.
  772. //
  773. Significand savedSignificand = significand;
  774. const fltSemantics *savedSemantics = semantics;
  775. fltSemantics extendedSemantics;
  776. opStatus status;
  777. unsigned int extendedPrecision;
  778. /* Normalize our MSB. */
  779. extendedPrecision = 2 * precision;
  780. if (omsb != extendedPrecision) {
  781. assert(extendedPrecision > omsb);
  782. APInt::tcShiftLeft(fullSignificand, newPartsCount,
  783. extendedPrecision - omsb);
  784. exponent -= extendedPrecision - omsb;
  785. }
  786. /* Create new semantics. */
  787. extendedSemantics = *semantics;
  788. extendedSemantics.precision = extendedPrecision;
  789. if (newPartsCount == 1)
  790. significand.part = fullSignificand[0];
  791. else
  792. significand.parts = fullSignificand;
  793. semantics = &extendedSemantics;
  794. APFloat extendedAddend(*addend);
  795. status = extendedAddend.convert(extendedSemantics, rmTowardZero, &ignored);
  796. assert(status == opOK);
  797. (void)status;
  798. lost_fraction = addOrSubtractSignificand(extendedAddend, false);
  799. /* Restore our state. */
  800. if (newPartsCount == 1)
  801. fullSignificand[0] = significand.part;
  802. significand = savedSignificand;
  803. semantics = savedSemantics;
  804. omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
  805. }
  806. // Convert the result having "2 * precision" significant-bits back to the one
  807. // having "precision" significant-bits. First, move the radix point from
  808. // poision "2*precision - 1" to "precision - 1". The exponent need to be
  809. // adjusted by "2*precision - 1" - "precision - 1" = "precision".
  810. exponent -= precision;
  811. // In case MSB resides at the left-hand side of radix point, shift the
  812. // mantissa right by some amount to make sure the MSB reside right before
  813. // the radix point (i.e. "MSB . rest-significant-bits").
  814. //
  815. // Note that the result is not normalized when "omsb < precision". So, the
  816. // caller needs to call APFloat::normalize() if normalized value is expected.
  817. if (omsb > precision) {
  818. unsigned int bits, significantParts;
  819. lostFraction lf;
  820. bits = omsb - precision;
  821. significantParts = partCountForBits(omsb);
  822. lf = shiftRight(fullSignificand, significantParts, bits);
  823. lost_fraction = combineLostFractions(lf, lost_fraction);
  824. exponent += bits;
  825. }
  826. APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
  827. if (newPartsCount > 4)
  828. delete [] fullSignificand;
  829. return lost_fraction;
  830. }
  831. /* Multiply the significands of LHS and RHS to DST. */
  832. lostFraction
  833. APFloat::divideSignificand(const APFloat &rhs)
  834. {
  835. unsigned int bit, i, partsCount;
  836. const integerPart *rhsSignificand;
  837. integerPart *lhsSignificand, *dividend, *divisor;
  838. integerPart scratch[4];
  839. lostFraction lost_fraction;
  840. assert(semantics == rhs.semantics);
  841. lhsSignificand = significandParts();
  842. rhsSignificand = rhs.significandParts();
  843. partsCount = partCount();
  844. if (partsCount > 2)
  845. dividend = new integerPart[partsCount * 2];
  846. else
  847. dividend = scratch;
  848. divisor = dividend + partsCount;
  849. /* Copy the dividend and divisor as they will be modified in-place. */
  850. for (i = 0; i < partsCount; i++) {
  851. dividend[i] = lhsSignificand[i];
  852. divisor[i] = rhsSignificand[i];
  853. lhsSignificand[i] = 0;
  854. }
  855. exponent -= rhs.exponent;
  856. unsigned int precision = semantics->precision;
  857. /* Normalize the divisor. */
  858. bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
  859. if (bit) {
  860. exponent += bit;
  861. APInt::tcShiftLeft(divisor, partsCount, bit);
  862. }
  863. /* Normalize the dividend. */
  864. bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
  865. if (bit) {
  866. exponent -= bit;
  867. APInt::tcShiftLeft(dividend, partsCount, bit);
  868. }
  869. /* Ensure the dividend >= divisor initially for the loop below.
  870. Incidentally, this means that the division loop below is
  871. guaranteed to set the integer bit to one. */
  872. if (APInt::tcCompare(dividend, divisor, partsCount) < 0) {
  873. exponent--;
  874. APInt::tcShiftLeft(dividend, partsCount, 1);
  875. assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
  876. }
  877. /* Long division. */
  878. for (bit = precision; bit; bit -= 1) {
  879. if (APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
  880. APInt::tcSubtract(dividend, divisor, 0, partsCount);
  881. APInt::tcSetBit(lhsSignificand, bit - 1);
  882. }
  883. APInt::tcShiftLeft(dividend, partsCount, 1);
  884. }
  885. /* Figure out the lost fraction. */
  886. int cmp = APInt::tcCompare(dividend, divisor, partsCount);
  887. if (cmp > 0)
  888. lost_fraction = lfMoreThanHalf;
  889. else if (cmp == 0)
  890. lost_fraction = lfExactlyHalf;
  891. else if (APInt::tcIsZero(dividend, partsCount))
  892. lost_fraction = lfExactlyZero;
  893. else
  894. lost_fraction = lfLessThanHalf;
  895. if (partsCount > 2)
  896. delete [] dividend;
  897. return lost_fraction;
  898. }
  899. unsigned int
  900. APFloat::significandMSB() const
  901. {
  902. return APInt::tcMSB(significandParts(), partCount());
  903. }
  904. unsigned int
  905. APFloat::significandLSB() const
  906. {
  907. return APInt::tcLSB(significandParts(), partCount());
  908. }
  909. /* Note that a zero result is NOT normalized to fcZero. */
  910. lostFraction
  911. APFloat::shiftSignificandRight(unsigned int bits)
  912. {
  913. /* Our exponent should not overflow. */
  914. assert((ExponentType) (exponent + bits) >= exponent);
  915. exponent += bits;
  916. return shiftRight(significandParts(), partCount(), bits);
  917. }
  918. /* Shift the significand left BITS bits, subtract BITS from its exponent. */
  919. void
  920. APFloat::shiftSignificandLeft(unsigned int bits)
  921. {
  922. assert(bits < semantics->precision);
  923. if (bits) {
  924. unsigned int partsCount = partCount();
  925. APInt::tcShiftLeft(significandParts(), partsCount, bits);
  926. exponent -= bits;
  927. assert(!APInt::tcIsZero(significandParts(), partsCount));
  928. }
  929. }
  930. APFloat::cmpResult
  931. APFloat::compareAbsoluteValue(const APFloat &rhs) const
  932. {
  933. int compare;
  934. assert(semantics == rhs.semantics);
  935. assert(isFiniteNonZero());
  936. assert(rhs.isFiniteNonZero());
  937. compare = exponent - rhs.exponent;
  938. /* If exponents are equal, do an unsigned bignum comparison of the
  939. significands. */
  940. if (compare == 0)
  941. compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
  942. partCount());
  943. if (compare > 0)
  944. return cmpGreaterThan;
  945. else if (compare < 0)
  946. return cmpLessThan;
  947. else
  948. return cmpEqual;
  949. }
  950. /* Handle overflow. Sign is preserved. We either become infinity or
  951. the largest finite number. */
  952. APFloat::opStatus
  953. APFloat::handleOverflow(roundingMode rounding_mode)
  954. {
  955. /* Infinity? */
  956. if (rounding_mode == rmNearestTiesToEven ||
  957. rounding_mode == rmNearestTiesToAway ||
  958. (rounding_mode == rmTowardPositive && !sign) ||
  959. (rounding_mode == rmTowardNegative && sign)) {
  960. category = fcInfinity;
  961. return (opStatus) (opOverflow | opInexact);
  962. }
  963. /* Otherwise we become the largest finite number. */
  964. category = fcNormal;
  965. exponent = semantics->maxExponent;
  966. APInt::tcSetLeastSignificantBits(significandParts(), partCount(),
  967. semantics->precision);
  968. return opInexact;
  969. }
  970. /* Returns TRUE if, when truncating the current number, with BIT the
  971. new LSB, with the given lost fraction and rounding mode, the result
  972. would need to be rounded away from zero (i.e., by increasing the
  973. signficand). This routine must work for fcZero of both signs, and
  974. fcNormal numbers. */
  975. bool
  976. APFloat::roundAwayFromZero(roundingMode rounding_mode,
  977. lostFraction lost_fraction,
  978. unsigned int bit) const
  979. {
  980. /* NaNs and infinities should not have lost fractions. */
  981. assert(isFiniteNonZero() || category == fcZero);
  982. /* Current callers never pass this so we don't handle it. */
  983. assert(lost_fraction != lfExactlyZero);
  984. switch (rounding_mode) {
  985. case rmNearestTiesToAway:
  986. return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf;
  987. case rmNearestTiesToEven:
  988. if (lost_fraction == lfMoreThanHalf)
  989. return true;
  990. /* Our zeroes don't have a significand to test. */
  991. if (lost_fraction == lfExactlyHalf && category != fcZero)
  992. return APInt::tcExtractBit(significandParts(), bit);
  993. return false;
  994. case rmTowardZero:
  995. return false;
  996. case rmTowardPositive:
  997. return sign == false;
  998. case rmTowardNegative:
  999. return sign == true;
  1000. }
  1001. llvm_unreachable("Invalid rounding mode found");
  1002. }
  1003. APFloat::opStatus
  1004. APFloat::normalize(roundingMode rounding_mode,
  1005. lostFraction lost_fraction)
  1006. {
  1007. unsigned int omsb; /* One, not zero, based MSB. */
  1008. int exponentChange;
  1009. if (!isFiniteNonZero())
  1010. return opOK;
  1011. /* Before rounding normalize the exponent of fcNormal numbers. */
  1012. omsb = significandMSB() + 1;
  1013. if (omsb) {
  1014. /* OMSB is numbered from 1. We want to place it in the integer
  1015. bit numbered PRECISION if possible, with a compensating change in
  1016. the exponent. */
  1017. exponentChange = omsb - semantics->precision;
  1018. /* If the resulting exponent is too high, overflow according to
  1019. the rounding mode. */
  1020. if (exponent + exponentChange > semantics->maxExponent)
  1021. return handleOverflow(rounding_mode);
  1022. /* Subnormal numbers have exponent minExponent, and their MSB
  1023. is forced based on that. */
  1024. if (exponent + exponentChange < semantics->minExponent)
  1025. exponentChange = semantics->minExponent - exponent;
  1026. /* Shifting left is easy as we don't lose precision. */
  1027. if (exponentChange < 0) {
  1028. assert(lost_fraction == lfExactlyZero);
  1029. shiftSignificandLeft(-exponentChange);
  1030. return opOK;
  1031. }
  1032. if (exponentChange > 0) {
  1033. lostFraction lf;
  1034. /* Shift right and capture any new lost fraction. */
  1035. lf = shiftSignificandRight(exponentChange);
  1036. lost_fraction = combineLostFractions(lf, lost_fraction);
  1037. /* Keep OMSB up-to-date. */
  1038. if (omsb > (unsigned) exponentChange)
  1039. omsb -= exponentChange;
  1040. else
  1041. omsb = 0;
  1042. }
  1043. }
  1044. /* Now round the number according to rounding_mode given the lost
  1045. fraction. */
  1046. /* As specified in IEEE 754, since we do not trap we do not report
  1047. underflow for exact results. */
  1048. if (lost_fraction == lfExactlyZero) {
  1049. /* Canonicalize zeroes. */
  1050. if (omsb == 0)
  1051. category = fcZero;
  1052. return opOK;
  1053. }
  1054. /* Increment the significand if we're rounding away from zero. */
  1055. if (roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
  1056. if (omsb == 0)
  1057. exponent = semantics->minExponent;
  1058. incrementSignificand();
  1059. omsb = significandMSB() + 1;
  1060. /* Did the significand increment overflow? */
  1061. if (omsb == (unsigned) semantics->precision + 1) {
  1062. /* Renormalize by incrementing the exponent and shifting our
  1063. significand right one. However if we already have the
  1064. maximum exponent we overflow to infinity. */
  1065. if (exponent == semantics->maxExponent) {
  1066. category = fcInfinity;
  1067. return (opStatus) (opOverflow | opInexact);
  1068. }
  1069. shiftSignificandRight(1);
  1070. return opInexact;
  1071. }
  1072. }
  1073. /* The normal case - we were and are not denormal, and any
  1074. significand increment above didn't overflow. */
  1075. if (omsb == semantics->precision)
  1076. return opInexact;
  1077. /* We have a non-zero denormal. */
  1078. assert(omsb < semantics->precision);
  1079. /* Canonicalize zeroes. */
  1080. if (omsb == 0)
  1081. category = fcZero;
  1082. /* The fcZero case is a denormal that underflowed to zero. */
  1083. return (opStatus) (opUnderflow | opInexact);
  1084. }
  1085. APFloat::opStatus
  1086. APFloat::addOrSubtractSpecials(const APFloat &rhs, bool subtract)
  1087. {
  1088. switch (PackCategoriesIntoKey(category, rhs.category)) {
  1089. default:
  1090. llvm_unreachable(0);
  1091. case PackCategoriesIntoKey(fcNaN, fcZero):
  1092. case PackCategoriesIntoKey(fcNaN, fcNormal):
  1093. case PackCategoriesIntoKey(fcNaN, fcInfinity):
  1094. case PackCategoriesIntoKey(fcNaN, fcNaN):
  1095. case PackCategoriesIntoKey(fcNormal, fcZero):
  1096. case PackCategoriesIntoKey(fcInfinity, fcNormal):
  1097. case PackCategoriesIntoKey(fcInfinity, fcZero):
  1098. return opOK;
  1099. case PackCategoriesIntoKey(fcZero, fcNaN):
  1100. case PackCategoriesIntoKey(fcNormal, fcNaN):
  1101. case PackCategoriesIntoKey(fcInfinity, fcNaN):
  1102. sign = false;
  1103. category = fcNaN;
  1104. copySignificand(rhs);
  1105. return opOK;
  1106. case PackCategoriesIntoKey(fcNormal, fcInfinity):
  1107. case PackCategoriesIntoKey(fcZero, fcInfinity):
  1108. category = fcInfinity;
  1109. sign = rhs.sign ^ subtract;
  1110. return opOK;
  1111. case PackCategoriesIntoKey(fcZero, fcNormal):
  1112. assign(rhs);
  1113. sign = rhs.sign ^ subtract;
  1114. return opOK;
  1115. case PackCategoriesIntoKey(fcZero, fcZero):
  1116. /* Sign depends on rounding mode; handled by caller. */
  1117. return opOK;
  1118. case PackCategoriesIntoKey(fcInfinity, fcInfinity):
  1119. /* Differently signed infinities can only be validly
  1120. subtracted. */
  1121. if (((sign ^ rhs.sign)!=0) != subtract) {
  1122. makeNaN();
  1123. return opInvalidOp;
  1124. }
  1125. return opOK;
  1126. case PackCategoriesIntoKey(fcNormal, fcNormal):
  1127. return opDivByZero;
  1128. }
  1129. }
  1130. /* Add or subtract two normal numbers. */
  1131. lostFraction
  1132. APFloat::addOrSubtractSignificand(const APFloat &rhs, bool subtract)
  1133. {
  1134. integerPart carry;
  1135. lostFraction lost_fraction;
  1136. int bits;
  1137. /* Determine if the operation on the absolute values is effectively
  1138. an addition or subtraction. */
  1139. subtract ^= (sign ^ rhs.sign) ? true : false;
  1140. /* Are we bigger exponent-wise than the RHS? */
  1141. bits = exponent - rhs.exponent;
  1142. /* Subtraction is more subtle than one might naively expect. */
  1143. if (subtract) {
  1144. APFloat temp_rhs(rhs);
  1145. bool reverse;
  1146. if (bits == 0) {
  1147. reverse = compareAbsoluteValue(temp_rhs) == cmpLessThan;
  1148. lost_fraction = lfExactlyZero;
  1149. } else if (bits > 0) {
  1150. lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
  1151. shiftSignificandLeft(1);
  1152. reverse = false;
  1153. } else {
  1154. lost_fraction = shiftSignificandRight(-bits - 1);
  1155. temp_rhs.shiftSignificandLeft(1);
  1156. reverse = true;
  1157. }
  1158. if (reverse) {
  1159. carry = temp_rhs.subtractSignificand
  1160. (*this, lost_fraction != lfExactlyZero);
  1161. copySignificand(temp_rhs);
  1162. sign = !sign;
  1163. } else {
  1164. carry = subtractSignificand
  1165. (temp_rhs, lost_fraction != lfExactlyZero);
  1166. }
  1167. /* Invert the lost fraction - it was on the RHS and
  1168. subtracted. */
  1169. if (lost_fraction == lfLessThanHalf)
  1170. lost_fraction = lfMoreThanHalf;
  1171. else if (lost_fraction == lfMoreThanHalf)
  1172. lost_fraction = lfLessThanHalf;
  1173. /* The code above is intended to ensure that no borrow is
  1174. necessary. */
  1175. assert(!carry);
  1176. (void)carry;
  1177. } else {
  1178. if (bits > 0) {
  1179. APFloat temp_rhs(rhs);
  1180. lost_fraction = temp_rhs.shiftSignificandRight(bits);
  1181. carry = addSignificand(temp_rhs);
  1182. } else {
  1183. lost_fraction = shiftSignificandRight(-bits);
  1184. carry = addSignificand(rhs);
  1185. }
  1186. /* We have a guard bit; generating a carry cannot happen. */
  1187. assert(!carry);
  1188. (void)carry;
  1189. }
  1190. return lost_fraction;
  1191. }
  1192. APFloat::opStatus
  1193. APFloat::multiplySpecials(const APFloat &rhs)
  1194. {
  1195. switch (PackCategoriesIntoKey(category, rhs.category)) {
  1196. default:
  1197. llvm_unreachable(0);
  1198. case PackCategoriesIntoKey(fcNaN, fcZero):
  1199. case PackCategoriesIntoKey(fcNaN, fcNormal):
  1200. case PackCategoriesIntoKey(fcNaN, fcInfinity):
  1201. case PackCategoriesIntoKey(fcNaN, fcNaN):
  1202. sign = false;
  1203. return opOK;
  1204. case PackCategoriesIntoKey(fcZero, fcNaN):
  1205. case PackCategoriesIntoKey(fcNormal, fcNaN):
  1206. case PackCategoriesIntoKey(fcInfinity, fcNaN):
  1207. sign = false;
  1208. category = fcNaN;
  1209. copySignificand(rhs);
  1210. return opOK;
  1211. case PackCategoriesIntoKey(fcNormal, fcInfinity):
  1212. case PackCategoriesIntoKey(fcInfinity, fcNormal):
  1213. case PackCategoriesIntoKey(fcInfinity, fcInfinity):
  1214. category = fcInfinity;
  1215. return opOK;
  1216. case PackCategoriesIntoKey(fcZero, fcNormal):
  1217. case PackCategoriesIntoKey(fcNormal, fcZero):
  1218. case PackCategoriesIntoKey(fcZero, fcZero):
  1219. category = fcZero;
  1220. return opOK;
  1221. case PackCategoriesIntoKey(fcZero, fcInfinity):
  1222. case PackCategoriesIntoKey(fcInfinity, fcZero):
  1223. makeNaN();
  1224. return opInvalidOp;
  1225. case PackCategoriesIntoKey(fcNormal, fcNormal):
  1226. return opOK;
  1227. }
  1228. }
  1229. APFloat::opStatus
  1230. APFloat::divideSpecials(const APFloat &rhs)
  1231. {
  1232. switch (PackCategoriesIntoKey(category, rhs.category)) {
  1233. default:
  1234. llvm_unreachable(0);
  1235. case PackCategoriesIntoKey(fcZero, fcNaN):
  1236. case PackCategoriesIntoKey(fcNormal, fcNaN):
  1237. case PackCategoriesIntoKey(fcInfinity, fcNaN):
  1238. category = fcNaN;
  1239. copySignificand(rhs);
  1240. case PackCategoriesIntoKey(fcNaN, fcZero):
  1241. case PackCategoriesIntoKey(fcNaN, fcNormal):
  1242. case PackCategoriesIntoKey(fcNaN, fcInfinity):
  1243. case PackCategoriesIntoKey(fcNaN, fcNaN):
  1244. sign = false;
  1245. case PackCategoriesIntoKey(fcInfinity, fcZero):
  1246. case PackCategoriesIntoKey(fcInfinity, fcNormal):
  1247. case PackCategoriesIntoKey(fcZero, fcInfinity):
  1248. case PackCategoriesIntoKey(fcZero, fcNormal):
  1249. return opOK;
  1250. case PackCategoriesIntoKey(fcNormal, fcInfinity):
  1251. category = fcZero;
  1252. return opOK;
  1253. case PackCategoriesIntoKey(fcNormal, fcZero):
  1254. category = fcInfinity;
  1255. return opDivByZero;
  1256. case PackCategoriesIntoKey(fcInfinity, fcInfinity):
  1257. case PackCategoriesIntoKey(fcZero, fcZero):
  1258. makeNaN();
  1259. return opInvalidOp;
  1260. case PackCategoriesIntoKey(fcNormal, fcNormal):
  1261. return opOK;
  1262. }
  1263. }
  1264. APFloat::opStatus
  1265. APFloat::modSpecials(const APFloat &rhs)
  1266. {
  1267. switch (PackCategoriesIntoKey(category, rhs.category)) {
  1268. default:
  1269. llvm_unreachable(0);
  1270. case PackCategoriesIntoKey(fcNaN, fcZero):
  1271. case PackCategoriesIntoKey(fcNaN, fcNormal):
  1272. case PackCategoriesIntoKey(fcNaN, fcInfinity):
  1273. case PackCategoriesIntoKey(fcNaN, fcNaN):
  1274. case PackCategoriesIntoKey(fcZero, fcInfinity):
  1275. case PackCategoriesIntoKey(fcZero, fcNormal):
  1276. case PackCategoriesIntoKey(fcNormal, fcInfinity):
  1277. return opOK;
  1278. case PackCategoriesIntoKey(fcZero, fcNaN):
  1279. case PackCategoriesIntoKey(fcNormal, fcNaN):
  1280. case PackCategoriesIntoKey(fcInfinity, fcNaN):
  1281. sign = false;
  1282. category = fcNaN;
  1283. copySignificand(rhs);
  1284. return opOK;
  1285. case PackCategoriesIntoKey(fcNormal, fcZero):
  1286. case PackCategoriesIntoKey(fcInfinity, fcZero):
  1287. case PackCategoriesIntoKey(fcInfinity, fcNormal):
  1288. case PackCategoriesIntoKey(fcInfinity, fcInfinity):
  1289. case PackCategoriesIntoKey(fcZero, fcZero):
  1290. makeNaN();
  1291. return opInvalidOp;
  1292. case PackCategoriesIntoKey(fcNormal, fcNormal):
  1293. return opOK;
  1294. }
  1295. }
  1296. /* Change sign. */
  1297. void
  1298. APFloat::changeSign()
  1299. {
  1300. /* Look mummy, this one's easy. */
  1301. sign = !sign;
  1302. }
  1303. void
  1304. APFloat::clearSign()
  1305. {
  1306. /* So is this one. */
  1307. sign = 0;
  1308. }
  1309. void
  1310. APFloat::copySign(const APFloat &rhs)
  1311. {
  1312. /* And this one. */
  1313. sign = rhs.sign;
  1314. }
  1315. /* Normalized addition or subtraction. */
  1316. APFloat::opStatus
  1317. APFloat::addOrSubtract(const APFloat &rhs, roundingMode rounding_mode,
  1318. bool subtract)
  1319. {
  1320. opStatus fs;
  1321. fs = addOrSubtractSpecials(rhs, subtract);
  1322. /* This return code means it was not a simple case. */
  1323. if (fs == opDivByZero) {
  1324. lostFraction lost_fraction;
  1325. lost_fraction = addOrSubtractSignificand(rhs, subtract);
  1326. fs = normalize(rounding_mode, lost_fraction);
  1327. /* Can only be zero if we lost no fraction. */
  1328. assert(category != fcZero || lost_fraction == lfExactlyZero);
  1329. }
  1330. /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
  1331. positive zero unless rounding to minus infinity, except that
  1332. adding two like-signed zeroes gives that zero. */
  1333. if (category == fcZero) {
  1334. if (rhs.category != fcZero || (sign == rhs.sign) == subtract)
  1335. sign = (rounding_mode == rmTowardNegative);
  1336. }
  1337. return fs;
  1338. }
  1339. /* Normalized addition. */
  1340. APFloat::opStatus
  1341. APFloat::add(const APFloat &rhs, roundingMode rounding_mode)
  1342. {
  1343. return addOrSubtract(rhs, rounding_mode, false);
  1344. }
  1345. /* Normalized subtraction. */
  1346. APFloat::opStatus
  1347. APFloat::subtract(const APFloat &rhs, roundingMode rounding_mode)
  1348. {
  1349. return addOrSubtract(rhs, rounding_mode, true);
  1350. }
  1351. /* Normalized multiply. */
  1352. APFloat::opStatus
  1353. APFloat::multiply(const APFloat &rhs, roundingMode rounding_mode)
  1354. {
  1355. opStatus fs;
  1356. sign ^= rhs.sign;
  1357. fs = multiplySpecials(rhs);
  1358. if (isFiniteNonZero()) {
  1359. lostFraction lost_fraction = multiplySignificand(rhs, 0);
  1360. fs = normalize(rounding_mode, lost_fraction);
  1361. if (lost_fraction != lfExactlyZero)
  1362. fs = (opStatus) (fs | opInexact);
  1363. }
  1364. return fs;
  1365. }
  1366. /* Normalized divide. */
  1367. APFloat::opStatus
  1368. APFloat::divide(const APFloat &rhs, roundingMode rounding_mode)
  1369. {
  1370. opStatus fs;
  1371. sign ^= rhs.sign;
  1372. fs = divideSpecials(rhs);
  1373. if (isFiniteNonZero()) {
  1374. lostFraction lost_fraction = divideSignificand(rhs);
  1375. fs = normalize(rounding_mode, lost_fraction);
  1376. if (lost_fraction != lfExactlyZero)
  1377. fs = (opStatus) (fs | opInexact);
  1378. }
  1379. return fs;
  1380. }
  1381. /* Normalized remainder. This is not currently correct in all cases. */
  1382. APFloat::opStatus
  1383. APFloat::remainder(const APFloat &rhs)
  1384. {
  1385. opStatus fs;
  1386. APFloat V = *this;
  1387. unsigned int origSign = sign;
  1388. fs = V.divide(rhs, rmNearestTiesToEven);
  1389. if (fs == opDivByZero)
  1390. return fs;
  1391. int parts = partCount();
  1392. integerPart *x = new integerPart[parts];
  1393. bool ignored;
  1394. fs = V.convertToInteger(x, parts * integerPartWidth, true,
  1395. rmNearestTiesToEven, &ignored);
  1396. if (fs==opInvalidOp)
  1397. return fs;
  1398. fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
  1399. rmNearestTiesToEven);
  1400. assert(fs==opOK); // should always work
  1401. fs = V.multiply(rhs, rmNearestTiesToEven);
  1402. assert(fs==opOK || fs==opInexact); // should not overflow or underflow
  1403. fs = subtract(V, rmNearestTiesToEven);
  1404. assert(fs==opOK || fs==opInexact); // likewise
  1405. if (isZero())
  1406. sign = origSign; // IEEE754 requires this
  1407. delete[] x;
  1408. return fs;
  1409. }
  1410. /* Normalized llvm frem (C fmod).
  1411. This is not currently correct in all cases. */
  1412. APFloat::opStatus
  1413. APFloat::mod(const APFloat &rhs, roundingMode rounding_mode)
  1414. {
  1415. opStatus fs;
  1416. fs = modSpecials(rhs);
  1417. if (isFiniteNonZero() && rhs.isFiniteNonZero()) {
  1418. APFloat V = *this;
  1419. unsigned int origSign = sign;
  1420. fs = V.divide(rhs, rmNearestTiesToEven);
  1421. if (fs == opDivByZero)
  1422. return fs;
  1423. int parts = partCount();
  1424. integerPart *x = new integerPart[parts];
  1425. bool ignored;
  1426. fs = V.convertToInteger(x, parts * integerPartWidth, true,
  1427. rmTowardZero, &ignored);
  1428. if (fs==opInvalidOp)
  1429. return fs;
  1430. fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
  1431. rmNearestTiesToEven);
  1432. assert(fs==opOK); // should always work
  1433. fs = V.multiply(rhs, rounding_mode);
  1434. assert(fs==opOK || fs==opInexact); // should not overflow or underflow
  1435. fs = subtract(V, rounding_mode);
  1436. assert(fs==opOK || fs==opInexact); // likewise
  1437. if (isZero())
  1438. sign = origSign; // IEEE754 requires this
  1439. delete[] x;
  1440. }
  1441. return fs;
  1442. }
  1443. /* Normalized fused-multiply-add. */
  1444. APFloat::opStatus
  1445. APFloat::fusedMultiplyAdd(const APFloat &multiplicand,
  1446. const APFloat &addend,
  1447. roundingMode rounding_mode)
  1448. {
  1449. opStatus fs;
  1450. /* Post-multiplication sign, before addition. */
  1451. sign ^= multiplicand.sign;
  1452. /* If and only if all arguments are normal do we need to do an
  1453. extended-precision calculation. */
  1454. if (isFiniteNonZero() &&
  1455. multiplicand.isFiniteNonZero() &&
  1456. addend.isFiniteNonZero()) {
  1457. lostFraction lost_fraction;
  1458. lost_fraction = multiplySignificand(multiplicand, &addend);
  1459. fs = normalize(rounding_mode, lost_fraction);
  1460. if (lost_fraction != lfExactlyZero)
  1461. fs = (opStatus) (fs | opInexact);
  1462. /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
  1463. positive zero unless rounding to minus infinity, except that
  1464. adding two like-signed zeroes gives that zero. */
  1465. if (category == fcZero && sign != addend.sign)
  1466. sign = (rounding_mode == rmTowardNegative);
  1467. } else {
  1468. fs = multiplySpecials(multiplicand);
  1469. /* FS can only be opOK or opInvalidOp. There is no more work
  1470. to do in the latter case. The IEEE-754R standard says it is
  1471. implementation-defined in this case whether, if ADDEND is a
  1472. quiet NaN, we raise invalid op; this implementation does so.
  1473. If we need to do the addition we can do so with normal
  1474. precision. */
  1475. if (fs == opOK)
  1476. fs = addOrSubtract(addend, rounding_mode, false);
  1477. }
  1478. return fs;
  1479. }
  1480. /* Rounding-mode corrrect round to integral value. */
  1481. APFloat::opStatus APFloat::roundToIntegral(roundingMode rounding_mode) {
  1482. opStatus fs;
  1483. // If the exponent is large enough, we know that this value is already
  1484. // integral, and the arithmetic below would potentially cause it to saturate
  1485. // to +/-Inf. Bail out early instead.
  1486. if (isFiniteNonZero() && exponent+1 >= (int)semanticsPrecision(*semantics))
  1487. return opOK;
  1488. // The algorithm here is quite simple: we add 2^(p-1), where p is the
  1489. // precision of our format, and then subtract it back off again. The choice
  1490. // of rounding modes for the addition/subtraction determines the rounding mode
  1491. // for our integral rounding as well.
  1492. // NOTE: When the input value is negative, we do subtraction followed by
  1493. // addition instead.
  1494. APInt IntegerConstant(NextPowerOf2(semanticsPrecision(*semantics)), 1);
  1495. IntegerConstant <<= semanticsPrecision(*semantics)-1;
  1496. APFloat MagicConstant(*semantics);
  1497. fs = MagicConstant.convertFromAPInt(IntegerConstant, false,
  1498. rmNearestTiesToEven);
  1499. MagicConstant.copySign(*this);
  1500. if (fs != opOK)
  1501. return fs;
  1502. // Preserve the input sign so that we can handle 0.0/-0.0 cases correctly.
  1503. bool inputSign = isNegative();
  1504. fs = add(MagicConstant, rounding_mode);
  1505. if (fs != opOK && fs != opInexact)
  1506. return fs;
  1507. fs = subtract(MagicConstant, rounding_mode);
  1508. // Restore the input sign.
  1509. if (inputSign != isNegative())
  1510. changeSign();
  1511. return fs;
  1512. }
  1513. /* Comparison requires normalized numbers. */
  1514. APFloat::cmpResult
  1515. APFloat::compare(const APFloat &rhs) const
  1516. {
  1517. cmpResult result;
  1518. assert(semantics == rhs.semantics);
  1519. switch (PackCategoriesIntoKey(category, rhs.category)) {
  1520. default:
  1521. llvm_unreachable(0);
  1522. case PackCategoriesIntoKey(fcNaN, fcZero):
  1523. case PackCategoriesIntoKey(fcNaN, fcNormal):
  1524. case PackCategoriesIntoKey(fcNaN, fcInfinity):
  1525. case PackCategoriesIntoKey(fcNaN, fcNaN):
  1526. case PackCategoriesIntoKey(fcZero, fcNaN):
  1527. case PackCategoriesIntoKey(fcNormal, fcNaN):
  1528. case PackCategoriesIntoKey(fcInfinity, fcNaN):
  1529. return cmpUnordered;
  1530. case PackCategoriesIntoKey(fcInfinity, fcNormal):
  1531. case PackCategoriesIntoKey(fcInfinity, fcZero):
  1532. case PackCategoriesIntoKey(fcNormal, fcZero):
  1533. if (sign)
  1534. return cmpLessThan;
  1535. else
  1536. return cmpGreaterThan;
  1537. case PackCategoriesIntoKey(fcNormal, fcInfinity):
  1538. case PackCategoriesIntoKey(fcZero, fcInfinity):
  1539. case PackCategoriesIntoKey(fcZero, fcNormal):
  1540. if (rhs.sign)
  1541. return cmpGreaterThan;
  1542. else
  1543. return cmpLessThan;
  1544. case PackCategoriesIntoKey(fcInfinity, fcInfinity):
  1545. if (sign == rhs.sign)
  1546. return cmpEqual;
  1547. else if (sign)
  1548. return cmpLessThan;
  1549. else
  1550. return cmpGreaterThan;
  1551. case PackCategoriesIntoKey(fcZero, fcZero):
  1552. return cmpEqual;
  1553. case PackCategoriesIntoKey(fcNormal, fcNormal):
  1554. break;
  1555. }
  1556. /* Two normal numbers. Do they have the same sign? */
  1557. if (sign != rhs.sign) {
  1558. if (sign)
  1559. result = cmpLessThan;
  1560. else
  1561. result = cmpGreaterThan;
  1562. } else {
  1563. /* Compare absolute values; invert result if negative. */
  1564. result = compareAbsoluteValue(rhs);
  1565. if (sign) {
  1566. if (result == cmpLessThan)
  1567. result = cmpGreaterThan;
  1568. else if (result == cmpGreaterThan)
  1569. result = cmpLessThan;
  1570. }
  1571. }
  1572. return result;
  1573. }
  1574. /// APFloat::convert - convert a value of one floating point type to another.
  1575. /// The return value corresponds to the IEEE754 exceptions. *losesInfo
  1576. /// records whether the transformation lost information, i.e. whether
  1577. /// converting the result back to the original type will produce the
  1578. /// original value (this is almost the same as return value==fsOK, but there
  1579. /// are edge cases where this is not so).
  1580. APFloat::opStatus
  1581. APFloat::convert(const fltSemantics &toSemantics,
  1582. roundingMode rounding_mode, bool *losesInfo)
  1583. {
  1584. lostFraction lostFraction;
  1585. unsigned int newPartCount, oldPartCount;
  1586. opStatus fs;
  1587. int shift;
  1588. const fltSemantics &fromSemantics = *semantics;
  1589. lostFraction = lfExactlyZero;
  1590. newPartCount = partCountForBits(toSemantics.precision + 1);
  1591. oldPartCount = partCount();
  1592. shift = toSemantics.precision - fromSemantics.precision;
  1593. bool X86SpecialNan = false;
  1594. if (&fromSemantics == &APFloat::x87DoubleExtended &&
  1595. &toSemantics != &APFloat::x87DoubleExtended && category == fcNaN &&
  1596. (!(*significandParts() & 0x8000000000000000ULL) ||
  1597. !(*significandParts() & 0x4000000000000000ULL))) {
  1598. // x86 has some unusual NaNs which cannot be represented in any other
  1599. // format; note them here.
  1600. X86SpecialNan = true;
  1601. }
  1602. // If this is a truncation of a denormal number, and the target semantics
  1603. // has larger exponent range than the source semantics (this can happen
  1604. // when truncating from PowerPC double-double to double format), the
  1605. // right shift could lose result mantissa bits. Adjust exponent instead
  1606. // of performing excessive shift.
  1607. if (shift < 0 && isFiniteNonZero()) {
  1608. int exponentChange = significandMSB() + 1 - fromSemantics.precision;
  1609. if (exponent + exponentChange < toSemantics.minExponent)
  1610. exponentChange = toSemantics.minExponent - exponent;
  1611. if (exponentChange < shift)
  1612. exponentChange = shift;
  1613. if (exponentChange < 0) {
  1614. shift -= exponentChange;
  1615. exponent += exponentChange;
  1616. }
  1617. }
  1618. // If this is a truncation, perform the shift before we narrow the storage.
  1619. if (shift < 0 && (isFiniteNonZero() || category==fcNaN))
  1620. lostFraction = shiftRight(significandParts(), oldPartCount, -shift);
  1621. // Fix the storage so it can hold to new value.
  1622. if (newPartCount > oldPartCount) {
  1623. // The new type requires more storage; make it available.
  1624. integerPart *newParts;
  1625. newParts = new integerPart[newPartCount];
  1626. APInt::tcSet(newParts, 0, newPartCount);
  1627. if (isFiniteNonZero() || category==fcNaN)
  1628. APInt::tcAssign(newParts, significandParts(), oldPartCount);
  1629. freeSignificand();
  1630. significand.parts = newParts;
  1631. } else if (newPartCount == 1 && oldPartCount != 1) {
  1632. // Switch to built-in storage for a single part.
  1633. integerPart newPart = 0;
  1634. if (isFiniteNonZero() || category==fcNaN)
  1635. newPart = significandParts()[0];
  1636. freeSignificand();
  1637. significand.part = newPart;
  1638. }
  1639. // Now that we have the right storage, switch the semantics.
  1640. semantics = &toSemantics;
  1641. // If this is an extension, perform the shift now that the storage is
  1642. // available.
  1643. if (shift > 0 && (isFiniteNonZero() || category==fcNaN))
  1644. APInt::tcShiftLeft(significandParts(), newPartCount, shift);
  1645. if (isFiniteNonZero()) {
  1646. fs = normalize(rounding_mode, lostFraction);
  1647. *losesInfo = (fs != opOK);
  1648. } else if (category == fcNaN) {
  1649. *losesInfo = lostFraction != lfExactlyZero || X86SpecialNan;
  1650. // For x87 extended precision, we want to make a NaN, not a special NaN if
  1651. // the input wasn't special either.
  1652. if (!X86SpecialNan && semantics == &APFloat::x87DoubleExtended)
  1653. APInt::tcSetBit(significandParts(), semantics->precision - 1);
  1654. // gcc forces the Quiet bit on, which means (float)(double)(float_sNan)
  1655. // does not give you back the same bits. This is dubious, and we
  1656. // don't currently do it. You're really supposed to get
  1657. // an invalid operation signal at runtime, but nobody does that.
  1658. fs = opOK;
  1659. } else {
  1660. *losesInfo = false;
  1661. fs = opOK;
  1662. }
  1663. return fs;
  1664. }
  1665. /* Convert a floating point number to an integer according to the
  1666. rounding mode. If the rounded integer value is out of range this
  1667. returns an invalid operation exception and the contents of the
  1668. destination parts are unspecified. If the rounded value is in
  1669. range but the floating point number is not the exact integer, the C
  1670. standard doesn't require an inexact exception to be raised. IEEE
  1671. 854 does require it so we do that.
  1672. Note that for conversions to integer type the C standard requires
  1673. round-to-zero to always be used. */
  1674. APFloat::opStatus
  1675. APFloat::convertToSignExtendedInteger(integerPart *parts, unsigned int width,
  1676. bool isSigned,
  1677. roundingMode rounding_mode,
  1678. bool *isExact) const
  1679. {
  1680. lostFraction lost_fraction;
  1681. const integerPart *src;
  1682. unsigned int dstPartsCount, truncatedBits;
  1683. *isExact = false;
  1684. /* Handle the three special cases first. */
  1685. if (category == fcInfinity || category == fcNaN)
  1686. return opInvalidOp;
  1687. dstPartsCount = partCountForBits(width);
  1688. if (category == fcZero) {
  1689. APInt::tcSet(parts, 0, dstPartsCount);
  1690. // Negative zero can't be represented as an int.
  1691. *isExact = !sign;
  1692. return opOK;
  1693. }
  1694. src = significandParts();
  1695. /* Step 1: place our absolute value, with any fraction truncated, in
  1696. the destination. */
  1697. if (exponent < 0) {
  1698. /* Our absolute value is less than one; truncate everything. */
  1699. APInt::tcSet(parts, 0, dstPartsCount);
  1700. /* For exponent -1 the integer bit represents .5, look at that.
  1701. For smaller exponents leftmost truncated bit is 0. */
  1702. truncatedBits = semantics->precision -1U - exponent;
  1703. } else {
  1704. /* We want the most significant (exponent + 1) bits; the rest are
  1705. truncated. */
  1706. unsigned int bits = exponent + 1U;
  1707. /* Hopelessly large in magnitude? */
  1708. if (bits > width)
  1709. return opInvalidOp;
  1710. if (bits < semantics->precision) {
  1711. /* We truncate (semantics->precision - bits) bits. */
  1712. truncatedBits = semantics->precision - bits;
  1713. APInt::tcExtract(parts, dstPartsCount, src, bits, truncatedBits);
  1714. } else {
  1715. /* We want at least as many bits as are available. */
  1716. APInt::tcExtract(parts, dstPartsCount, src, semantics->precision, 0);
  1717. APInt::tcShiftLeft(parts, dstPartsCount, bits - semantics->precision);
  1718. truncatedBits = 0;
  1719. }
  1720. }
  1721. /* Step 2: work out any lost fraction, and increment the absolute
  1722. value if we would round away from zero. */
  1723. if (truncatedBits) {
  1724. lost_fraction = lostFractionThroughTruncation(src, partCount(),
  1725. truncatedBits);
  1726. if (lost_fraction != lfExactlyZero &&
  1727. roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) {
  1728. if (APInt::tcIncrement(parts, dstPartsCount))
  1729. return opInvalidOp; /* Overflow. */
  1730. }
  1731. } else {
  1732. lost_fraction = lfExactlyZero;
  1733. }
  1734. /* Step 3: check if we fit in the destination. */
  1735. unsigned int omsb = APInt::tcMSB(parts, dstPartsCount) + 1;
  1736. if (sign) {
  1737. if (!isSigned) {
  1738. /* Negative numbers cannot be represented as unsigned. */
  1739. if (omsb != 0)
  1740. return opInvalidOp;
  1741. } else {
  1742. /* It takes omsb bits to represent the unsigned integer value.
  1743. We lose a bit for the sign, but care is needed as the
  1744. maximally negative integer is a special case. */
  1745. if (omsb == width && APInt::tcLSB(parts, dstPartsCount) + 1 != omsb)
  1746. return opInvalidOp;
  1747. /* This case can happen because of rounding. */
  1748. if (omsb > width)
  1749. return opInvalidOp;
  1750. }
  1751. APInt::tcNegate (parts, dstPartsCount);
  1752. } else {
  1753. if (omsb >= width + !isSigned)
  1754. return opInvalidOp;
  1755. }
  1756. if (lost_fraction == lfExactlyZero) {
  1757. *isExact = true;
  1758. return opOK;
  1759. } else
  1760. return opInexact;
  1761. }
  1762. /* Same as convertToSignExtendedInteger, except we provide
  1763. deterministic values in case of an invalid operation exception,
  1764. namely zero for NaNs and the minimal or maximal value respectively
  1765. for underflow or overflow.
  1766. The *isExact output tells whether the result is exact, in the sense
  1767. that converting it back to the original floating point type produces
  1768. the original value. This is almost equivalent to result==opOK,
  1769. except for negative zeroes.
  1770. */
  1771. APFloat::opStatus
  1772. APFloat::convertToInteger(integerPart *parts, unsigned int width,
  1773. bool isSigned,
  1774. roundingMode rounding_mode, bool *isExact) const
  1775. {
  1776. opStatus fs;
  1777. fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode,
  1778. isExact);
  1779. if (fs == opInvalidOp) {
  1780. unsigned int bits, dstPartsCount;
  1781. dstPartsCount = partCountForBits(width);
  1782. if (category == fcNaN)
  1783. bits = 0;
  1784. else if (sign)
  1785. bits = isSigned;
  1786. else
  1787. bits = width - isSigned;
  1788. APInt::tcSetLeastSignificantBits(parts, dstPartsCount, bits);
  1789. if (sign && isSigned)
  1790. APInt::tcShiftLeft(parts, dstPartsCount, width - 1);
  1791. }
  1792. return fs;
  1793. }
  1794. /* Same as convertToInteger(integerPart*, ...), except the result is returned in
  1795. an APSInt, whose initial bit-width and signed-ness are used to determine the
  1796. precision of the conversion.
  1797. */
  1798. APFloat::opStatus
  1799. APFloat::convertToInteger(APSInt &result,
  1800. roundingMode rounding_mode, bool *isExact) const
  1801. {
  1802. unsigned bitWidth = result.getBitWidth();
  1803. SmallVector<uint64_t, 4> parts(result.getNumWords());
  1804. opStatus status = convertToInteger(
  1805. parts.data(), bitWidth, result.isSigned(), rounding_mode, isExact);
  1806. // Keeps the original signed-ness.
  1807. result = APInt(bitWidth, parts);
  1808. return status;
  1809. }
  1810. /* Convert an unsigned integer SRC to a floating point number,
  1811. rounding according to ROUNDING_MODE. The sign of the floating
  1812. point number is not modified. */
  1813. APFloat::opStatus
  1814. APFloat::convertFromUnsignedParts(const integerPart *src,
  1815. unsigned int srcCount,
  1816. roundingMode rounding_mode)
  1817. {
  1818. unsigned int omsb, precision, dstCount;
  1819. integerPart *dst;
  1820. lostFraction lost_fraction;
  1821. category = fcNormal;
  1822. omsb = APInt::tcMSB(src, srcCount) + 1;
  1823. dst = significandParts();
  1824. dstCount = partCount();
  1825. precision = semantics->precision;
  1826. /* We want the most significant PRECISION bits of SRC. There may not
  1827. be that many; extract what we can. */
  1828. if (precision <= omsb) {
  1829. exponent = omsb - 1;
  1830. lost_fraction = lostFractionThroughTruncation(src, srcCount,
  1831. omsb - precision);
  1832. APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
  1833. } else {
  1834. exponent = precision - 1;
  1835. lost_fraction = lfExactlyZero;
  1836. APInt::tcExtract(dst, dstCount, src, omsb, 0);
  1837. }
  1838. return normalize(rounding_mode, lost_fraction);
  1839. }
  1840. APFloat::opStatus
  1841. APFloat::convertFromAPInt(const APInt &Val,
  1842. bool isSigned,
  1843. roundingMode rounding_mode)
  1844. {
  1845. unsigned int partCount = Val.getNumWords();
  1846. APInt api = Val;
  1847. sign = false;
  1848. if (isSigned && api.isNegative()) {
  1849. sign = true;
  1850. api = -api;
  1851. }
  1852. return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
  1853. }
  1854. /* Convert a two's complement integer SRC to a floating point number,
  1855. rounding according to ROUNDING_MODE. ISSIGNED is true if the
  1856. integer is signed, in which case it must be sign-extended. */
  1857. APFloat::opStatus
  1858. APFloat::convertFromSignExtendedInteger(const integerPart *src,
  1859. unsigned int srcCount,
  1860. bool isSigned,
  1861. roundingMode rounding_mode)
  1862. {
  1863. opStatus status;
  1864. if (isSigned &&
  1865. APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) {
  1866. integerPart *copy;
  1867. /* If we're signed and negative negate a copy. */
  1868. sign = true;
  1869. copy = new integerPart[srcCount];
  1870. APInt::tcAssign(copy, src, srcCount);
  1871. APInt::tcNegate(copy, srcCount);
  1872. status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
  1873. delete [] copy;
  1874. } else {
  1875. sign = false;
  1876. status = convertFromUnsignedParts(src, srcCount, rounding_mode);
  1877. }
  1878. return status;
  1879. }
  1880. /* FIXME: should this just take a const APInt reference? */
  1881. APFloat::opStatus
  1882. APFloat::convertFromZeroExtendedInteger(const integerPart *parts,
  1883. unsigned int width, bool isSigned,
  1884. roundingMode rounding_mode)
  1885. {
  1886. unsigned int partCount = partCountForBits(width);
  1887. APInt api = APInt(width, makeArrayRef(parts, partCount));
  1888. sign = false;
  1889. if (isSigned && APInt::tcExtractBit(parts, width - 1)) {
  1890. sign = true;
  1891. api = -api;
  1892. }
  1893. return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
  1894. }
  1895. APFloat::opStatus
  1896. APFloat::convertFromHexadecimalString(StringRef s, roundingMode rounding_mode)
  1897. {
  1898. lostFraction lost_fraction = lfExactlyZero;
  1899. category = fcNormal;
  1900. zeroSignificand();
  1901. exponent = 0;
  1902. integerPart *significand = significandParts();
  1903. unsigned partsCount = partCount();
  1904. unsigned bitPos = partsCount * integerPartWidth;
  1905. bool computedTrailingFraction = false;
  1906. // Skip leading zeroes and any (hexa)decimal point.
  1907. StringRef::iterator begin = s.begin();
  1908. StringRef::iterator end = s.end();
  1909. StringRef::iterator dot;
  1910. StringRef::iterator p = skipLeadingZeroesAndAnyDot(begin, end, &dot);
  1911. StringRef::iterator firstSignificantDigit = p;
  1912. while (p != end) {
  1913. integerPart hex_value;
  1914. if (*p == '.') {
  1915. assert(dot == end && "String contains multiple dots");
  1916. dot = p++;
  1917. continue;
  1918. }
  1919. hex_value = hexDigitValue(*p);
  1920. if (hex_value == -1U)
  1921. break;
  1922. p++;
  1923. // Store the number while we have space.
  1924. if (bitPos) {
  1925. bitPos -= 4;
  1926. hex_value <<= bitPos % integerPartWidth;
  1927. significand[bitPos / integerPartWidth] |= hex_value;
  1928. } else if (!computedTrailingFraction) {
  1929. lost_fraction = trailingHexadecimalFraction(p, end, hex_value);
  1930. computedTrailingFraction = true;
  1931. }
  1932. }
  1933. /* Hex floats require an exponent but not a hexadecimal point. */
  1934. assert(p != end && "Hex strings require an exponent");
  1935. assert((*p == 'p' || *p == 'P') && "Invalid character in significand");
  1936. assert(p != begin && "Significand has no digits");
  1937. assert((dot == end || p - begin != 1) && "Significand has no digits");
  1938. /* Ignore the exponent if we are zero. */
  1939. if (p != firstSignificantDigit) {
  1940. int expAdjustment;
  1941. /* Implicit hexadecimal point? */
  1942. if (dot == end)
  1943. dot = p;
  1944. /* Calculate the exponent adjustment implicit in the number of
  1945. significant digits. */
  1946. expAdjustment = static_cast<int>(dot - firstSignificantDigit);
  1947. if (expAdjustment < 0)
  1948. expAdjustment++;
  1949. expAdjustment = expAdjustment * 4 - 1;
  1950. /* Adjust for writing the significand starting at the most
  1951. significant nibble. */
  1952. expAdjustment += semantics->precision;
  1953. expAdjustment -= partsCount * integerPartWidth;
  1954. /* Adjust for the given exponent. */
  1955. exponent = totalExponent(p + 1, end, expAdjustment);
  1956. }
  1957. return normalize(rounding_mode, lost_fraction);
  1958. }
  1959. APFloat::opStatus
  1960. APFloat::roundSignificandWithExponent(const integerPart *decSigParts,
  1961. unsigned sigPartCount, int exp,
  1962. roundingMode rounding_mode)
  1963. {
  1964. unsigned int parts, pow5PartCount;
  1965. fltSemantics calcSemantics = { 32767, -32767, 0 };
  1966. integerPart pow5Parts[maxPowerOfFiveParts];
  1967. bool isNearest;
  1968. isNearest = (rounding_mode == rmNearestTiesToEven ||
  1969. rounding_mode == rmNearestTiesToAway);
  1970. parts = partCountForBits(semantics->precision + 11);
  1971. /* Calculate pow(5, abs(exp)). */
  1972. pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp: -exp);
  1973. for (;; parts *= 2) {
  1974. opStatus sigStatus, powStatus;
  1975. unsigned int excessPrecision, truncatedBits;
  1976. calcSemantics.precision = parts * integerPartWidth - 1;
  1977. excessPrecision = calcSemantics.precision - semantics->precision;
  1978. truncatedBits = excessPrecision;
  1979. APFloat decSig = APFloat::getZero(calcSemantics, sign);
  1980. APFloat pow5(calcSemantics);
  1981. sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount,
  1982. rmNearestTiesToEven);
  1983. powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
  1984. rmNearestTiesToEven);
  1985. /* Add exp, as 10^n = 5^n * 2^n. */
  1986. decSig.exponent += exp;
  1987. lostFraction calcLostFraction;
  1988. integerPart HUerr, HUdistance;
  1989. unsigned int powHUerr;
  1990. if (exp >= 0) {
  1991. /* multiplySignificand leaves the precision-th bit set to 1. */
  1992. calcLostFraction = decSig.multiplySignificand(pow5, NULL);
  1993. powHUerr = powStatus != opOK;
  1994. } else {
  1995. calcLostFraction = decSig.divideSignificand(pow5);
  1996. /* Denormal numbers have less precision. */
  1997. if (decSig.exponent < semantics->minExponent) {
  1998. excessPrecision += (semantics->minExponent - decSig.exponent);
  1999. truncatedBits = excessPrecision;
  2000. if (excessPrecision > calcSemantics.precision)
  2001. excessPrecision = calcSemantics.precision;
  2002. }
  2003. /* Extra half-ulp lost in reciprocal of exponent. */
  2004. powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0:2;
  2005. }
  2006. /* Both multiplySignificand and divideSignificand return the
  2007. result with the integer bit set. */
  2008. assert(APInt::tcExtractBit
  2009. (decSig.significandParts(), calcSemantics.precision - 1) == 1);
  2010. HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK,
  2011. powHUerr);
  2012. HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(),
  2013. excessPrecision, isNearest);
  2014. /* Are we guaranteed to round correctly if we truncate? */
  2015. if (HUdistance >= HUerr) {
  2016. APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
  2017. calcSemantics.precision - excessPrecision,
  2018. excessPrecision);
  2019. /* Take the exponent of decSig. If we tcExtract-ed less bits
  2020. above we must adjust our exponent to compensate for the
  2021. implicit right shift. */
  2022. exponent = (decSig.exponent + semantics->precision
  2023. - (calcSemantics.precision - excessPrecision));
  2024. calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(),
  2025. decSig.partCount(),
  2026. truncatedBits);
  2027. return normalize(rounding_mode, calcLostFraction);
  2028. }
  2029. }
  2030. }
  2031. APFloat::opStatus
  2032. APFloat::convertFromDecimalString(StringRef str, roundingMode rounding_mode)
  2033. {
  2034. decimalInfo D;
  2035. opStatus fs;
  2036. /* Scan the text. */
  2037. StringRef::iterator p = str.begin();
  2038. interpretDecimal(p, str.end(), &D);
  2039. /* Handle the quick cases. First the case of no significant digits,
  2040. i.e. zero, and then exponents that are obviously too large or too
  2041. small. Writing L for log 10 / log 2, a number d.ddddd*10^exp
  2042. definitely overflows if
  2043. (exp - 1) * L >= maxExponent
  2044. and definitely underflows to zero where
  2045. (exp + 1) * L <= minExponent - precision
  2046. With integer arithmetic the tightest bounds for L are
  2047. 93/28 < L < 196/59 [ numerator <= 256 ]
  2048. 42039/12655 < L < 28738/8651 [ numerator <= 65536 ]
  2049. */
  2050. // Test if we have a zero number allowing for strings with no null terminators
  2051. // and zero decimals with non-zero exponents.
  2052. //
  2053. // We computed firstSigDigit by ignoring all zeros and dots. Thus if
  2054. // D->firstSigDigit equals str.end(), every digit must be a zero and there can
  2055. // be at most one dot. On the other hand, if we have a zero with a non-zero
  2056. // exponent, then we know that D.firstSigDigit will be non-numeric.
  2057. if (D.firstSigDigit == str.end() || decDigitValue(*D.firstSigDigit) >= 10U) {
  2058. category = fcZero;
  2059. fs = opOK;
  2060. /* Check whether the normalized exponent is high enough to overflow
  2061. max during the log-rebasing in the max-exponent check below. */
  2062. } else if (D.normalizedExponent - 1 > INT_MAX / 42039) {
  2063. fs = handleOverflow(rounding_mode);
  2064. /* If it wasn't, then it also wasn't high enough to overflow max
  2065. during the log-rebasing in the min-exponent check. Check that it
  2066. won't overflow min in either check, then perform the min-exponent
  2067. check. */
  2068. } else if (D.normalizedExponent - 1 < INT_MIN / 42039 ||
  2069. (D.normalizedExponent + 1) * 28738 <=
  2070. 8651 * (semantics->minExponent - (int) semantics->precision)) {
  2071. /* Underflow to zero and round. */
  2072. category = fcNormal;
  2073. zeroSignificand();
  2074. fs = normalize(rounding_mode, lfLessThanHalf);
  2075. /* We can finally safely perform the max-exponent check. */
  2076. } else if ((D.normalizedExponent - 1) * 42039
  2077. >= 12655 * semantics->maxExponent) {
  2078. /* Overflow and round. */
  2079. fs = handleOverflow(rounding_mode);
  2080. } else {
  2081. integerPart *decSignificand;
  2082. unsigned int partCount;
  2083. /* A tight upper bound on number of bits required to hold an
  2084. N-digit decimal integer is N * 196 / 59. Allocate enough space
  2085. to hold the full significand, and an extra part required by
  2086. tcMultiplyPart. */
  2087. partCount = static_cast<unsigned int>(D.lastSigDigit - D.firstSigDigit) + 1;
  2088. partCount = partCountForBits(1 + 196 * partCount / 59);
  2089. decSignificand = new integerPart[partCount + 1];
  2090. partCount = 0;
  2091. /* Convert to binary efficiently - we do almost all multiplication
  2092. in an integerPart. When this would overflow do we do a single
  2093. bignum multiplication, and then revert again to multiplication
  2094. in an integerPart. */
  2095. do {
  2096. integerPart decValue, val, multiplier;
  2097. val = 0;
  2098. multiplier = 1;
  2099. do {
  2100. if (*p == '.') {
  2101. p++;
  2102. if (p == str.end()) {
  2103. break;
  2104. }
  2105. }
  2106. decValue = decDigitValue(*p++);
  2107. assert(decValue < 10U && "Invalid character in significand");
  2108. multiplier *= 10;
  2109. val = val * 10 + decValue;
  2110. /* The maximum number that can be multiplied by ten with any
  2111. digit added without overflowing an integerPart. */
  2112. } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10);
  2113. /* Multiply out the current part. */
  2114. APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val,
  2115. partCount, partCount + 1, false);
  2116. /* If we used another part (likely but not guaranteed), increase
  2117. the count. */
  2118. if (decSignificand[partCount])
  2119. partCount++;
  2120. } while (p <= D.lastSigDigit);
  2121. category = fcNormal;
  2122. fs = roundSignificandWithExponent(decSignificand, partCount,
  2123. D.exponent, rounding_mode);
  2124. delete [] decSignificand;
  2125. }
  2126. return fs;
  2127. }
  2128. bool
  2129. APFloat::convertFromStringSpecials(StringRef str) {
  2130. if (str.equals("inf") || str.equals("INFINITY")) {
  2131. makeInf(false);
  2132. return true;
  2133. }
  2134. if (str.equals("-inf") || str.equals("-INFINITY")) {
  2135. makeInf(true);
  2136. return true;
  2137. }
  2138. if (str.equals("nan") || str.equals("NaN")) {
  2139. makeNaN(false, false);
  2140. return true;
  2141. }
  2142. if (str.equals("-nan") || str.equals("-NaN")) {
  2143. makeNaN(false, true);
  2144. return true;
  2145. }
  2146. return false;
  2147. }
  2148. APFloat::opStatus
  2149. APFloat::convertFromString(StringRef str, roundingMode rounding_mode)
  2150. {
  2151. assert(!str.empty() && "Invalid string length");
  2152. // Handle special cases.
  2153. if (convertFromStringSpecials(str))
  2154. return opOK;
  2155. /* Handle a leading minus sign. */
  2156. StringRef::iterator p = str.begin();
  2157. size_t slen = str.size();
  2158. sign = *p == '-' ? 1 : 0;
  2159. if (*p == '-' || *p == '+') {
  2160. p++;
  2161. slen--;
  2162. assert(slen && "String has no digits");
  2163. }
  2164. if (slen >= 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
  2165. assert(slen - 2 && "Invalid string");
  2166. return convertFromHexadecimalString(StringRef(p + 2, slen - 2),
  2167. rounding_mode);
  2168. }
  2169. return convertFromDecimalString(StringRef(p, slen), rounding_mode);
  2170. }
  2171. /* Write out a hexadecimal representation of the floating point value
  2172. to DST, which must be of sufficient size, in the C99 form
  2173. [-]0xh.hhhhp[+-]d. Return the number of characters written,
  2174. excluding the terminating NUL.
  2175. If UPPERCASE, the output is in upper case, otherwise in lower case.
  2176. HEXDIGITS digits appear altogether, rounding the value if
  2177. necessary. If HEXDIGITS is 0, the minimal precision to display the
  2178. number precisely is used instead. If nothing would appear after
  2179. the decimal point it is suppressed.
  2180. The decimal exponent is always printed and has at least one digit.
  2181. Zero values display an exponent of zero. Infinities and NaNs
  2182. appear as "infinity" or "nan" respectively.
  2183. The above rules are as specified by C99. There is ambiguity about
  2184. what the leading hexadecimal digit should be. This implementation
  2185. uses whatever is necessary so that the exponent is displayed as
  2186. stored. This implies the exponent will fall within the IEEE format
  2187. range, and the leading hexadecimal digit will be 0 (for denormals),
  2188. 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
  2189. any other digits zero).
  2190. */
  2191. unsigned int
  2192. APFloat::convertToHexString(char *dst, unsigned int hexDigits,
  2193. bool upperCase, roundingMode rounding_mode) const
  2194. {
  2195. char *p;
  2196. p = dst;
  2197. if (sign)
  2198. *dst++ = '-';
  2199. switch (category) {
  2200. case fcInfinity:
  2201. memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1);
  2202. dst += sizeof infinityL - 1;
  2203. break;
  2204. case fcNaN:
  2205. memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
  2206. dst += sizeof NaNU - 1;
  2207. break;
  2208. case fcZero:
  2209. *dst++ = '0';
  2210. *dst++ = upperCase ? 'X': 'x';
  2211. *dst++ = '0';
  2212. if (hexDigits > 1) {
  2213. *dst++ = '.';
  2214. memset (dst, '0', hexDigits - 1);
  2215. dst += hexDigits - 1;
  2216. }
  2217. *dst++ = upperCase ? 'P': 'p';
  2218. *dst++ = '0';
  2219. break;
  2220. case fcNormal:
  2221. dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
  2222. break;
  2223. }
  2224. *dst = 0;
  2225. return static_cast<unsigned int>(dst - p);
  2226. }
  2227. /* Does the hard work of outputting the correctly rounded hexadecimal
  2228. form of a normal floating point number with the specified number of
  2229. hexadecimal digits. If HEXDIGITS is zero the minimum number of
  2230. digits necessary to print the value precisely is output. */
  2231. char *
  2232. APFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
  2233. bool upperCase,
  2234. roundingMode rounding_mode) const
  2235. {
  2236. unsigned int count, valueBits, shift, partsCount, outputDigits;
  2237. const char *hexDigitChars;
  2238. const integerPart *significand;
  2239. char *p;
  2240. bool roundUp;
  2241. *dst++ = '0';
  2242. *dst++ = upperCase ? 'X': 'x';
  2243. roundUp = false;
  2244. hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower;
  2245. significand = significandParts();
  2246. partsCount = partCount();
  2247. /* +3 because the first digit only uses the single integer bit, so
  2248. we have 3 virtual zero most-significant-bits. */
  2249. valueBits = semantics->precision + 3;
  2250. shift = integerPartWidth - valueBits % integerPartWidth;
  2251. /* The natural number of digits required ignoring trailing
  2252. insignificant zeroes. */
  2253. outputDigits = (valueBits - significandLSB () + 3) / 4;
  2254. /* hexDigits of zero means use the required number for the
  2255. precision. Otherwise, see if we are truncating. If we are,
  2256. find out if we need to round away from zero. */
  2257. if (hexDigits) {
  2258. if (hexDigits < outputDigits) {
  2259. /* We are dropping non-zero bits, so need to check how to round.
  2260. "bits" is the number of dropped bits. */
  2261. unsigned int bits;
  2262. lostFraction fraction;
  2263. bits = valueBits - hexDigits * 4;
  2264. fraction = lostFractionThroughTruncation (significand, partsCount, bits);
  2265. roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
  2266. }
  2267. outputDigits = hexDigits;
  2268. }
  2269. /* Write the digits consecutively, and start writing in the location
  2270. of the hexadecimal point. We move the most significant digit
  2271. left and add the hexadecimal point later. */
  2272. p = ++dst;
  2273. count = (valueBits + integerPartWidth - 1) / integerPartWidth;
  2274. while (outputDigits && count) {
  2275. integerPart part;
  2276. /* Put the most significant integerPartWidth bits in "part". */
  2277. if (--count == partsCount)
  2278. part = 0; /* An imaginary higher zero part. */
  2279. else
  2280. part = significand[count] << shift;
  2281. if (count && shift)
  2282. part |= significand[count - 1] >> (integerPartWidth - shift);
  2283. /* Convert as much of "part" to hexdigits as we can. */
  2284. unsigned int curDigits = integerPartWidth / 4;
  2285. if (curDigits > outputDigits)
  2286. curDigits = outputDigits;
  2287. dst += partAsHex (dst, part, curDigits, hexDigitChars);
  2288. outputDigits -= curDigits;
  2289. }
  2290. if (roundUp) {
  2291. char *q = dst;
  2292. /* Note that hexDigitChars has a trailing '0'. */
  2293. do {
  2294. q--;
  2295. *q = hexDigitChars[hexDigitValue (*q) + 1];
  2296. } while (*q == '0');
  2297. assert(q >= p);
  2298. } else {
  2299. /* Add trailing zeroes. */
  2300. memset (dst, '0', outputDigits);
  2301. dst += outputDigits;
  2302. }
  2303. /* Move the most significant digit to before the point, and if there
  2304. is something after the decimal point add it. This must come
  2305. after rounding above. */
  2306. p[-1] = p[0];
  2307. if (dst -1 == p)
  2308. dst--;
  2309. else
  2310. p[0] = '.';
  2311. /* Finally output the exponent. */
  2312. *dst++ = upperCase ? 'P': 'p';
  2313. return writeSignedDecimal (dst, exponent);
  2314. }
  2315. hash_code llvm::hash_value(const APFloat &Arg) {
  2316. if (!Arg.isFiniteNonZero())
  2317. return hash_combine((uint8_t)Arg.category,
  2318. // NaN has no sign, fix it at zero.
  2319. Arg.isNaN() ? (uint8_t)0 : (uint8_t)Arg.sign,
  2320. Arg.semantics->precision);
  2321. // Normal floats need their exponent and significand hashed.
  2322. return hash_combine((uint8_t)Arg.category, (uint8_t)Arg.sign,
  2323. Arg.semantics->precision, Arg.exponent,
  2324. hash_combine_range(
  2325. Arg.significandParts(),
  2326. Arg.significandParts() + Arg.partCount()));
  2327. }
  2328. // Conversion from APFloat to/from host float/double. It may eventually be
  2329. // possible to eliminate these and have everybody deal with APFloats, but that
  2330. // will take a while. This approach will not easily extend to long double.
  2331. // Current implementation requires integerPartWidth==64, which is correct at
  2332. // the moment but could be made more general.
  2333. // Denormals have exponent minExponent in APFloat, but minExponent-1 in
  2334. // the actual IEEE respresentations. We compensate for that here.
  2335. APInt
  2336. APFloat::convertF80LongDoubleAPFloatToAPInt() const
  2337. {
  2338. assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended);
  2339. assert(partCount()==2);
  2340. uint64_t myexponent, mysignificand;
  2341. if (isFiniteNonZero()) {
  2342. myexponent = exponent+16383; //bias
  2343. mysignificand = significandParts()[0];
  2344. if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL))
  2345. myexponent = 0; // denormal
  2346. } else if (category==fcZero) {
  2347. myexponent = 0;
  2348. mysignificand = 0;
  2349. } else if (category==fcInfinity) {
  2350. myexponent = 0x7fff;
  2351. mysignificand = 0x8000000000000000ULL;
  2352. } else {
  2353. assert(category == fcNaN && "Unknown category");
  2354. myexponent = 0x7fff;
  2355. mysignificand = significandParts()[0];
  2356. }
  2357. uint64_t words[2];
  2358. words[0] = mysignificand;
  2359. words[1] = ((uint64_t)(sign & 1) << 15) |
  2360. (myexponent & 0x7fffLL);
  2361. return APInt(80, words);
  2362. }
  2363. APInt
  2364. APFloat::convertPPCDoubleDoubleAPFloatToAPInt() const
  2365. {
  2366. assert(semantics == (const llvm::fltSemantics*)&PPCDoubleDouble);
  2367. assert(partCount()==2);
  2368. uint64_t words[2];
  2369. opStatus fs;
  2370. bool losesInfo;
  2371. // Convert number to double. To avoid spurious underflows, we re-
  2372. // normalize against the "double" minExponent first, and only *then*
  2373. // truncate the mantissa. The result of that second conversion
  2374. // may be inexact, but should never underflow.
  2375. // Declare fltSemantics before APFloat that uses it (and
  2376. // saves pointer to it) to ensure correct destruction order.
  2377. fltSemantics extendedSemantics = *semantics;
  2378. extendedSemantics.minExponent = IEEEdouble.minExponent;
  2379. APFloat extended(*this);
  2380. fs = extended.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
  2381. assert(fs == opOK && !losesInfo);
  2382. (void)fs;
  2383. APFloat u(extended);
  2384. fs = u.convert(IEEEdouble, rmNearestTiesToEven, &losesInfo);
  2385. assert(fs == opOK || fs == opInexact);
  2386. (void)fs;
  2387. words[0] = *u.convertDoubleAPFloatToAPInt().getRawData();
  2388. // If conversion was exact or resulted in a special case, we're done;
  2389. // just set the second double to zero. Otherwise, re-convert back to
  2390. // the extended format and compute the difference. This now should
  2391. // convert exactly to double.
  2392. if (u.isFiniteNonZero() && losesInfo) {
  2393. fs = u.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
  2394. assert(fs == opOK && !losesInfo);
  2395. (void)fs;
  2396. APFloat v(extended);
  2397. v.subtract(u, rmNearestTiesToEven);
  2398. fs = v.convert(IEEEdouble, rmNearestTiesToEven, &losesInfo);
  2399. assert(fs == opOK && !losesInfo);
  2400. (void)fs;
  2401. words[1] = *v.convertDoubleAPFloatToAPInt().getRawData();
  2402. } else {
  2403. words[1] = 0;
  2404. }
  2405. return APInt(128, words);
  2406. }
  2407. APInt
  2408. APFloat::convertQuadrupleAPFloatToAPInt() const
  2409. {
  2410. assert(semantics == (const llvm::fltSemantics*)&IEEEquad);
  2411. assert(partCount()==2);
  2412. uint64_t myexponent, mysignificand, mysignificand2;
  2413. if (isFiniteNonZero()) {
  2414. myexponent = exponent+16383; //bias
  2415. mysignificand = significandParts()[0];
  2416. mysignificand2 = significandParts()[1];
  2417. if (myexponent==1 && !(mysignificand2 & 0x1000000000000LL))
  2418. myexponent = 0; // denormal
  2419. } else if (category==fcZero) {
  2420. myexponent = 0;
  2421. mysignificand = mysignificand2 = 0;
  2422. } else if (category==fcInfinity) {
  2423. myexponent = 0x7fff;
  2424. mysignificand = mysignificand2 = 0;
  2425. } else {
  2426. assert(category == fcNaN && "Unknown category!");
  2427. myexponent = 0x7fff;
  2428. mysignificand = significandParts()[0];
  2429. mysignificand2 = significandParts()[1];
  2430. }
  2431. uint64_t words[2];
  2432. words[0] = mysignificand;
  2433. words[1] = ((uint64_t)(sign & 1) << 63) |
  2434. ((myexponent & 0x7fff) << 48) |
  2435. (mysignificand2 & 0xffffffffffffLL);
  2436. return APInt(128, words);
  2437. }
  2438. APInt
  2439. APFloat::convertDoubleAPFloatToAPInt() const
  2440. {
  2441. assert(semantics == (const llvm::fltSemantics*)&IEEEdouble);
  2442. assert(partCount()==1);
  2443. uint64_t myexponent, mysignificand;
  2444. if (isFiniteNonZero()) {
  2445. myexponent = exponent+1023; //bias
  2446. mysignificand = *significandParts();
  2447. if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
  2448. myexponent = 0; // denormal
  2449. } else if (category==fcZero) {
  2450. myexponent = 0;
  2451. mysignificand = 0;
  2452. } else if (category==fcInfinity) {
  2453. myexponent = 0x7ff;
  2454. mysignificand = 0;
  2455. } else {
  2456. assert(category == fcNaN && "Unknown category!");
  2457. myexponent = 0x7ff;
  2458. mysignificand = *significandParts();
  2459. }
  2460. return APInt(64, ((((uint64_t)(sign & 1) << 63) |
  2461. ((myexponent & 0x7ff) << 52) |
  2462. (mysignificand & 0xfffffffffffffLL))));
  2463. }
  2464. APInt
  2465. APFloat::convertFloatAPFloatToAPInt() const
  2466. {
  2467. assert(semantics == (const llvm::fltSemantics*)&IEEEsingle);
  2468. assert(partCount()==1);
  2469. uint32_t myexponent, mysignificand;
  2470. if (isFiniteNonZero()) {
  2471. myexponent = exponent+127; //bias
  2472. mysignificand = (uint32_t)*significandParts();
  2473. if (myexponent == 1 && !(mysignificand & 0x800000))
  2474. myexponent = 0; // denormal
  2475. } else if (category==fcZero) {
  2476. myexponent = 0;
  2477. mysignificand = 0;
  2478. } else if (category==fcInfinity) {
  2479. myexponent = 0xff;
  2480. mysignificand = 0;
  2481. } else {
  2482. assert(category == fcNaN && "Unknown category!");
  2483. myexponent = 0xff;
  2484. mysignificand = (uint32_t)*significandParts();
  2485. }
  2486. return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) |
  2487. (mysignificand & 0x7fffff)));
  2488. }
  2489. APInt
  2490. APFloat::convertHalfAPFloatToAPInt() const
  2491. {
  2492. assert(semantics == (const llvm::fltSemantics*)&IEEEhalf);
  2493. assert(partCount()==1);
  2494. uint32_t myexponent, mysignificand;
  2495. if (isFiniteNonZero()) {
  2496. myexponent = exponent+15; //bias
  2497. mysignificand = (uint32_t)*significandParts();
  2498. if (myexponent == 1 && !(mysignificand & 0x400))
  2499. myexponent = 0; // denormal
  2500. } else if (category==fcZero) {
  2501. myexponent = 0;
  2502. mysignificand = 0;
  2503. } else if (category==fcInfinity) {
  2504. myexponent = 0x1f;
  2505. mysignificand = 0;
  2506. } else {
  2507. assert(category == fcNaN && "Unknown category!");
  2508. myexponent = 0x1f;
  2509. mysignificand = (uint32_t)*significandParts();
  2510. }
  2511. return APInt(16, (((sign&1) << 15) | ((myexponent&0x1f) << 10) |
  2512. (mysignificand & 0x3ff)));
  2513. }
  2514. // This function creates an APInt that is just a bit map of the floating
  2515. // point constant as it would appear in memory. It is not a conversion,
  2516. // and treating the result as a normal integer is unlikely to be useful.
  2517. APInt
  2518. APFloat::bitcastToAPInt() const
  2519. {
  2520. if (semantics == (const llvm::fltSemantics*)&IEEEhalf)
  2521. return convertHalfAPFloatToAPInt();
  2522. if (semantics == (const llvm::fltSemantics*)&IEEEsingle)
  2523. return convertFloatAPFloatToAPInt();
  2524. if (semantics == (const llvm::fltSemantics*)&IEEEdouble)
  2525. return convertDoubleAPFloatToAPInt();
  2526. if (semantics == (const llvm::fltSemantics*)&IEEEquad)
  2527. return convertQuadrupleAPFloatToAPInt();
  2528. if (semantics == (const llvm::fltSemantics*)&PPCDoubleDouble)
  2529. return convertPPCDoubleDoubleAPFloatToAPInt();
  2530. assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended &&
  2531. "unknown format!");
  2532. return convertF80LongDoubleAPFloatToAPInt();
  2533. }
  2534. float
  2535. APFloat::convertToFloat() const
  2536. {
  2537. assert(semantics == (const llvm::fltSemantics*)&IEEEsingle &&
  2538. "Float semantics are not IEEEsingle");
  2539. APInt api = bitcastToAPInt();
  2540. return api.bitsToFloat();
  2541. }
  2542. double
  2543. APFloat::convertToDouble() const
  2544. {
  2545. assert(semantics == (const llvm::fltSemantics*)&IEEEdouble &&
  2546. "Float semantics are not IEEEdouble");
  2547. APInt api = bitcastToAPInt();
  2548. return api.bitsToDouble();
  2549. }
  2550. /// Integer bit is explicit in this format. Intel hardware (387 and later)
  2551. /// does not support these bit patterns:
  2552. /// exponent = all 1's, integer bit 0, significand 0 ("pseudoinfinity")
  2553. /// exponent = all 1's, integer bit 0, significand nonzero ("pseudoNaN")
  2554. /// exponent = 0, integer bit 1 ("pseudodenormal")
  2555. /// exponent!=0 nor all 1's, integer bit 0 ("unnormal")
  2556. /// At the moment, the first two are treated as NaNs, the second two as Normal.
  2557. void
  2558. APFloat::initFromF80LongDoubleAPInt(const APInt &api)
  2559. {
  2560. assert(api.getBitWidth()==80);
  2561. uint64_t i1 = api.getRawData()[0];
  2562. uint64_t i2 = api.getRawData()[1];
  2563. uint64_t myexponent = (i2 & 0x7fff);
  2564. uint64_t mysignificand = i1;
  2565. initialize(&APFloat::x87DoubleExtended);
  2566. assert(partCount()==2);
  2567. sign = static_cast<unsigned int>(i2>>15);
  2568. if (myexponent==0 && mysignificand==0) {
  2569. // exponent, significand meaningless
  2570. category = fcZero;
  2571. } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) {
  2572. // exponent, significand meaningless
  2573. category = fcInfinity;
  2574. } else if (myexponent==0x7fff && mysignificand!=0x8000000000000000ULL) {
  2575. // exponent meaningless
  2576. category = fcNaN;
  2577. significandParts()[0] = mysignificand;
  2578. significandParts()[1] = 0;
  2579. } else {
  2580. category = fcNormal;
  2581. exponent = myexponent - 16383;
  2582. significandParts()[0] = mysignificand;
  2583. significandParts()[1] = 0;
  2584. if (myexponent==0) // denormal
  2585. exponent = -16382;
  2586. }
  2587. }
  2588. void
  2589. APFloat::initFromPPCDoubleDoubleAPInt(const APInt &api)
  2590. {
  2591. assert(api.getBitWidth()==128);
  2592. uint64_t i1 = api.getRawData()[0];
  2593. uint64_t i2 = api.getRawData()[1];
  2594. opStatus fs;
  2595. bool losesInfo;
  2596. // Get the first double and convert to our format.
  2597. initFromDoubleAPInt(APInt(64, i1));
  2598. fs = convert(PPCDoubleDouble, rmNearestTiesToEven, &losesInfo);
  2599. assert(fs == opOK && !losesInfo);
  2600. (void)fs;
  2601. // Unless we have a special case, add in second double.
  2602. if (isFiniteNonZero()) {
  2603. APFloat v(IEEEdouble, APInt(64, i2));
  2604. fs = v.convert(PPCDoubleDouble, rmNearestTiesToEven, &losesInfo);
  2605. assert(fs == opOK && !losesInfo);
  2606. (void)fs;
  2607. add(v, rmNearestTiesToEven);
  2608. }
  2609. }
  2610. void
  2611. APFloat::initFromQuadrupleAPInt(const APInt &api)
  2612. {
  2613. assert(api.getBitWidth()==128);
  2614. uint64_t i1 = api.getRawData()[0];
  2615. uint64_t i2 = api.getRawData()[1];
  2616. uint64_t myexponent = (i2 >> 48) & 0x7fff;
  2617. uint64_t mysignificand = i1;
  2618. uint64_t mysignificand2 = i2 & 0xffffffffffffLL;
  2619. initialize(&APFloat::IEEEquad);
  2620. assert(partCount()==2);
  2621. sign = static_cast<unsigned int>(i2>>63);
  2622. if (myexponent==0 &&
  2623. (mysignificand==0 && mysignificand2==0)) {
  2624. // exponent, significand meaningless
  2625. category = fcZero;
  2626. } else if (myexponent==0x7fff &&
  2627. (mysignificand==0 && mysignificand2==0)) {
  2628. // exponent, significand meaningless
  2629. category = fcInfinity;
  2630. } else if (myexponent==0x7fff &&
  2631. (mysignificand!=0 || mysignificand2 !=0)) {
  2632. // exponent meaningless
  2633. category = fcNaN;
  2634. significandParts()[0] = mysignificand;
  2635. significandParts()[1] = mysignificand2;
  2636. } else {
  2637. category = fcNormal;
  2638. exponent = myexponent - 16383;
  2639. significandParts()[0] = mysignificand;
  2640. significandParts()[1] = mysignificand2;
  2641. if (myexponent==0) // denormal
  2642. exponent = -16382;
  2643. else
  2644. significandParts()[1] |= 0x1000000000000LL; // integer bit
  2645. }
  2646. }
  2647. void
  2648. APFloat::initFromDoubleAPInt(const APInt &api)
  2649. {
  2650. assert(api.getBitWidth()==64);
  2651. uint64_t i = *api.getRawData();
  2652. uint64_t myexponent = (i >> 52) & 0x7ff;
  2653. uint64_t mysignificand = i & 0xfffffffffffffLL;
  2654. initialize(&APFloat::IEEEdouble);
  2655. assert(partCount()==1);
  2656. sign = static_cast<unsigned int>(i>>63);
  2657. if (myexponent==0 && mysignificand==0) {
  2658. // exponent, significand meaningless
  2659. category = fcZero;
  2660. } else if (myexponent==0x7ff && mysignificand==0) {
  2661. // exponent, significand meaningless
  2662. category = fcInfinity;
  2663. } else if (myexponent==0x7ff && mysignificand!=0) {
  2664. // exponent meaningless
  2665. category = fcNaN;
  2666. *significandParts() = mysignificand;
  2667. } else {
  2668. category = fcNormal;
  2669. exponent = myexponent - 1023;
  2670. *significandParts() = mysignificand;
  2671. if (myexponent==0) // denormal
  2672. exponent = -1022;
  2673. else
  2674. *significandParts() |= 0x10000000000000LL; // integer bit
  2675. }
  2676. }
  2677. void
  2678. APFloat::initFromFloatAPInt(const APInt & api)
  2679. {
  2680. assert(api.getBitWidth()==32);
  2681. uint32_t i = (uint32_t)*api.getRawData();
  2682. uint32_t myexponent = (i >> 23) & 0xff;
  2683. uint32_t mysignificand = i & 0x7fffff;
  2684. initialize(&APFloat::IEEEsingle);
  2685. assert(partCount()==1);
  2686. sign = i >> 31;
  2687. if (myexponent==0 && mysignificand==0) {
  2688. // exponent, significand meaningless
  2689. category = fcZero;
  2690. } else if (myexponent==0xff && mysignificand==0) {
  2691. // exponent, significand meaningless
  2692. category = fcInfinity;
  2693. } else if (myexponent==0xff && mysignificand!=0) {
  2694. // sign, exponent, significand meaningless
  2695. category = fcNaN;
  2696. *significandParts() = mysignificand;
  2697. } else {
  2698. category = fcNormal;
  2699. exponent = myexponent - 127; //bias
  2700. *significandParts() = mysignificand;
  2701. if (myexponent==0) // denormal
  2702. exponent = -126;
  2703. else
  2704. *significandParts() |= 0x800000; // integer bit
  2705. }
  2706. }
  2707. void
  2708. APFloat::initFromHalfAPInt(const APInt & api)
  2709. {
  2710. assert(api.getBitWidth()==16);
  2711. uint32_t i = (uint32_t)*api.getRawData();
  2712. uint32_t myexponent = (i >> 10) & 0x1f;
  2713. uint32_t mysignificand = i & 0x3ff;
  2714. initialize(&APFloat::IEEEhalf);
  2715. assert(partCount()==1);
  2716. sign = i >> 15;
  2717. if (myexponent==0 && mysignificand==0) {
  2718. // exponent, significand meaningless
  2719. category = fcZero;
  2720. } else if (myexponent==0x1f && mysignificand==0) {
  2721. // exponent, significand meaningless
  2722. category = fcInfinity;
  2723. } else if (myexponent==0x1f && mysignificand!=0) {
  2724. // sign, exponent, significand meaningless
  2725. category = fcNaN;
  2726. *significandParts() = mysignificand;
  2727. } else {
  2728. category = fcNormal;
  2729. exponent = myexponent - 15; //bias
  2730. *significandParts() = mysignificand;
  2731. if (myexponent==0) // denormal
  2732. exponent = -14;
  2733. else
  2734. *significandParts() |= 0x400; // integer bit
  2735. }
  2736. }
  2737. /// Treat api as containing the bits of a floating point number. Currently
  2738. /// we infer the floating point type from the size of the APInt. The
  2739. /// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful
  2740. /// when the size is anything else).
  2741. void
  2742. APFloat::initFromAPInt(const fltSemantics* Sem, const APInt& api)
  2743. {
  2744. if (Sem == &IEEEhalf)
  2745. return initFromHalfAPInt(api);
  2746. if (Sem == &IEEEsingle)
  2747. return initFromFloatAPInt(api);
  2748. if (Sem == &IEEEdouble)
  2749. return initFromDoubleAPInt(api);
  2750. if (Sem == &x87DoubleExtended)
  2751. return initFromF80LongDoubleAPInt(api);
  2752. if (Sem == &IEEEquad)
  2753. return initFromQuadrupleAPInt(api);
  2754. if (Sem == &PPCDoubleDouble)
  2755. return initFromPPCDoubleDoubleAPInt(api);
  2756. llvm_unreachable(0);
  2757. }
  2758. APFloat
  2759. APFloat::getAllOnesValue(unsigned BitWidth, bool isIEEE)
  2760. {
  2761. switch (BitWidth) {
  2762. case 16:
  2763. return APFloat(IEEEhalf, APInt::getAllOnesValue(BitWidth));
  2764. case 32:
  2765. return APFloat(IEEEsingle, APInt::getAllOnesValue(BitWidth));
  2766. case 64:
  2767. return APFloat(IEEEdouble, APInt::getAllOnesValue(BitWidth));
  2768. case 80:
  2769. return APFloat(x87DoubleExtended, APInt::getAllOnesValue(BitWidth));
  2770. case 128:
  2771. if (isIEEE)
  2772. return APFloat(IEEEquad, APInt::getAllOnesValue(BitWidth));
  2773. return APFloat(PPCDoubleDouble, APInt::getAllOnesValue(BitWidth));
  2774. default:
  2775. llvm_unreachable("Unknown floating bit width");
  2776. }
  2777. }
  2778. /// Make this number the largest magnitude normal number in the given
  2779. /// semantics.
  2780. void APFloat::makeLargest(bool Negative) {
  2781. // We want (in interchange format):
  2782. // sign = {Negative}
  2783. // exponent = 1..10
  2784. // significand = 1..1
  2785. category = fcNormal;
  2786. sign = Negative;
  2787. exponent = semantics->maxExponent;
  2788. // Use memset to set all but the highest integerPart to all ones.
  2789. integerPart *significand = significandParts();
  2790. unsigned PartCount = partCount();
  2791. memset(significand, 0xFF, sizeof(integerPart)*(PartCount - 1));
  2792. // Set the high integerPart especially setting all unused top bits for
  2793. // internal consistency.
  2794. const unsigned NumUnusedHighBits =
  2795. PartCount*integerPartWidth - semantics->precision;
  2796. significand[PartCount - 1] = ~integerPart(0) >> NumUnusedHighBits;
  2797. }
  2798. /// Make this number the smallest magnitude denormal number in the given
  2799. /// semantics.
  2800. void APFloat::makeSmallest(bool Negative) {
  2801. // We want (in interchange format):
  2802. // sign = {Negative}
  2803. // exponent = 0..0
  2804. // significand = 0..01
  2805. category = fcNormal;
  2806. sign = Negative;
  2807. exponent = semantics->minExponent;
  2808. APInt::tcSet(significandParts(), 1, partCount());
  2809. }
  2810. APFloat APFloat::getLargest(const fltSemantics &Sem, bool Negative) {
  2811. // We want (in interchange format):
  2812. // sign = {Negative}
  2813. // exponent = 1..10
  2814. // significand = 1..1
  2815. APFloat Val(Sem, uninitialized);
  2816. Val.makeLargest(Negative);
  2817. return Val;
  2818. }
  2819. APFloat APFloat::getSmallest(const fltSemantics &Sem, bool Negative) {
  2820. // We want (in interchange format):
  2821. // sign = {Negative}
  2822. // exponent = 0..0
  2823. // significand = 0..01
  2824. APFloat Val(Sem, uninitialized);
  2825. Val.makeSmallest(Negative);
  2826. return Val;
  2827. }
  2828. APFloat APFloat::getSmallestNormalized(const fltSemantics &Sem, bool Negative) {
  2829. APFloat Val(Sem, uninitialized);
  2830. // We want (in interchange format):
  2831. // sign = {Negative}
  2832. // exponent = 0..0
  2833. // significand = 10..0
  2834. Val.category = fcNormal;
  2835. Val.zeroSignificand();
  2836. Val.sign = Negative;
  2837. Val.exponent = Sem.minExponent;
  2838. Val.significandParts()[partCountForBits(Sem.precision)-1] |=
  2839. (((integerPart) 1) << ((Sem.precision - 1) % integerPartWidth));
  2840. return Val;
  2841. }
  2842. APFloat::APFloat(const fltSemantics &Sem, const APInt &API) {
  2843. initFromAPInt(&Sem, API);
  2844. }
  2845. APFloat::APFloat(float f) {
  2846. initFromAPInt(&IEEEsingle, APInt::floatToBits(f));
  2847. }
  2848. APFloat::APFloat(double d) {
  2849. initFromAPInt(&IEEEdouble, APInt::doubleToBits(d));
  2850. }
  2851. namespace {
  2852. void append(SmallVectorImpl<char> &Buffer, StringRef Str) {
  2853. Buffer.append(Str.begin(), Str.end());
  2854. }
  2855. /// Removes data from the given significand until it is no more
  2856. /// precise than is required for the desired precision.
  2857. void AdjustToPrecision(APInt &significand,
  2858. int &exp, unsigned FormatPrecision) {
  2859. unsigned bits = significand.getActiveBits();
  2860. // 196/59 is a very slight overestimate of lg_2(10).
  2861. unsigned bitsRequired = (FormatPrecision * 196 + 58) / 59;
  2862. if (bits <= bitsRequired) return;
  2863. unsigned tensRemovable = (bits - bitsRequired) * 59 / 196;
  2864. if (!tensRemovable) return;
  2865. exp += tensRemovable;
  2866. APInt divisor(significand.getBitWidth(), 1);
  2867. APInt powten(significand.getBitWidth(), 10);
  2868. while (true) {
  2869. if (tensRemovable & 1)
  2870. divisor *= powten;
  2871. tensRemovable >>= 1;
  2872. if (!tensRemovable) break;
  2873. powten *= powten;
  2874. }
  2875. significand = significand.udiv(divisor);
  2876. // Truncate the significand down to its active bit count.
  2877. significand = significand.trunc(significand.getActiveBits());
  2878. }
  2879. void AdjustToPrecision(SmallVectorImpl<char> &buffer,
  2880. int &exp, unsigned FormatPrecision) {
  2881. unsigned N = buffer.size();
  2882. if (N <= FormatPrecision) return;
  2883. // The most significant figures are the last ones in the buffer.
  2884. unsigned FirstSignificant = N - FormatPrecision;
  2885. // Round.
  2886. // FIXME: this probably shouldn't use 'round half up'.
  2887. // Rounding down is just a truncation, except we also want to drop
  2888. // trailing zeros from the new result.
  2889. if (buffer[FirstSignificant - 1] < '5') {
  2890. while (FirstSignificant < N && buffer[FirstSignificant] == '0')
  2891. FirstSignificant++;
  2892. exp += FirstSignificant;
  2893. buffer.erase(&buffer[0], &buffer[FirstSignificant]);
  2894. return;
  2895. }
  2896. // Rounding up requires a decimal add-with-carry. If we continue
  2897. // the carry, the newly-introduced zeros will just be truncated.
  2898. for (unsigned I = FirstSignificant; I != N; ++I) {
  2899. if (buffer[I] == '9') {
  2900. FirstSignificant++;
  2901. } else {
  2902. buffer[I]++;
  2903. break;
  2904. }
  2905. }
  2906. // If we carried through, we have exactly one digit of precision.
  2907. if (FirstSignificant == N) {
  2908. exp += FirstSignificant;
  2909. buffer.clear();
  2910. buffer.push_back('1');
  2911. return;
  2912. }
  2913. exp += FirstSignificant;
  2914. buffer.erase(&buffer[0], &buffer[FirstSignificant]);
  2915. }
  2916. }
  2917. void APFloat::toString(SmallVectorImpl<char> &Str,
  2918. unsigned FormatPrecision,
  2919. unsigned FormatMaxPadding) const {
  2920. switch (category) {
  2921. case fcInfinity:
  2922. if (isNegative())
  2923. return append(Str, "-Inf");
  2924. else
  2925. return append(Str, "+Inf");
  2926. case fcNaN: return append(Str, "NaN");
  2927. case fcZero:
  2928. if (isNegative())
  2929. Str.push_back('-');
  2930. if (!FormatMaxPadding)
  2931. append(Str, "0.0E+0");
  2932. else
  2933. Str.push_back('0');
  2934. return;
  2935. case fcNormal:
  2936. break;
  2937. }
  2938. if (isNegative())
  2939. Str.push_back('-');
  2940. // Decompose the number into an APInt and an exponent.
  2941. int exp = exponent - ((int) semantics->precision - 1);
  2942. APInt significand(semantics->precision,
  2943. makeArrayRef(significandParts(),
  2944. partCountForBits(semantics->precision)));
  2945. // Set FormatPrecision if zero. We want to do this before we
  2946. // truncate trailing zeros, as those are part of the precision.
  2947. if (!FormatPrecision) {
  2948. // We use enough digits so the number can be round-tripped back to an
  2949. // APFloat. The formula comes from "How to Print Floating-Point Numbers
  2950. // Accurately" by Steele and White.
  2951. // FIXME: Using a formula based purely on the precision is conservative;
  2952. // we can print fewer digits depending on the actual value being printed.
  2953. // FormatPrecision = 2 + floor(significandBits / lg_2(10))
  2954. FormatPrecision = 2 + semantics->precision * 59 / 196;
  2955. }
  2956. // Ignore trailing binary zeros.
  2957. int trailingZeros = significand.countTrailingZeros();
  2958. exp += trailingZeros;
  2959. significand = significand.lshr(trailingZeros);
  2960. // Change the exponent from 2^e to 10^e.
  2961. if (exp == 0) {
  2962. // Nothing to do.
  2963. } else if (exp > 0) {
  2964. // Just shift left.
  2965. significand = significand.zext(semantics->precision + exp);
  2966. significand <<= exp;
  2967. exp = 0;
  2968. } else { /* exp < 0 */
  2969. int texp = -exp;
  2970. // We transform this using the identity:
  2971. // (N)(2^-e) == (N)(5^e)(10^-e)
  2972. // This means we have to multiply N (the significand) by 5^e.
  2973. // To avoid overflow, we have to operate on numbers large
  2974. // enough to store N * 5^e:
  2975. // log2(N * 5^e) == log2(N) + e * log2(5)
  2976. // <= semantics->precision + e * 137 / 59
  2977. // (log_2(5) ~ 2.321928 < 2.322034 ~ 137/59)
  2978. unsigned precision = semantics->precision + (137 * texp + 136) / 59;
  2979. // Multiply significand by 5^e.
  2980. // N * 5^0101 == N * 5^(1*1) * 5^(0*2) * 5^(1*4) * 5^(0*8)
  2981. significand = significand.zext(precision);
  2982. APInt five_to_the_i(precision, 5);
  2983. while (true) {
  2984. if (texp & 1) significand *= five_to_the_i;
  2985. texp >>= 1;
  2986. if (!texp) break;
  2987. five_to_the_i *= five_to_the_i;
  2988. }
  2989. }
  2990. AdjustToPrecision(significand, exp, FormatPrecision);
  2991. SmallVector<char, 256> buffer;
  2992. // Fill the buffer.
  2993. unsigned precision = significand.getBitWidth();
  2994. APInt ten(precision, 10);
  2995. APInt digit(precision, 0);
  2996. bool inTrail = true;
  2997. while (significand != 0) {
  2998. // digit <- significand % 10
  2999. // significand <- significand / 10
  3000. APInt::udivrem(significand, ten, significand, digit);
  3001. unsigned d = digit.getZExtValue();
  3002. // Drop trailing zeros.
  3003. if (inTrail && !d) exp++;
  3004. else {
  3005. buffer.push_back((char) ('0' + d));
  3006. inTrail = false;
  3007. }
  3008. }
  3009. assert(!buffer.empty() && "no characters in buffer!");
  3010. // Drop down to FormatPrecision.
  3011. // TODO: don't do more precise calculations above than are required.
  3012. AdjustToPrecision(buffer, exp, FormatPrecision);
  3013. unsigned NDigits = buffer.size();
  3014. // Check whether we should use scientific notation.
  3015. bool FormatScientific;
  3016. if (!FormatMaxPadding)
  3017. FormatScientific = true;
  3018. else {
  3019. if (exp >= 0) {
  3020. // 765e3 --> 765000
  3021. // ^^^
  3022. // But we shouldn't make the number look more precise than it is.
  3023. FormatScientific = ((unsigned) exp > FormatMaxPadding ||
  3024. NDigits + (unsigned) exp > FormatPrecision);
  3025. } else {
  3026. // Power of the most significant digit.
  3027. int MSD = exp + (int) (NDigits - 1);
  3028. if (MSD >= 0) {
  3029. // 765e-2 == 7.65
  3030. FormatScientific = false;
  3031. } else {
  3032. // 765e-5 == 0.00765
  3033. // ^ ^^
  3034. FormatScientific = ((unsigned) -MSD) > FormatMaxPadding;
  3035. }
  3036. }
  3037. }
  3038. // Scientific formatting is pretty straightforward.
  3039. if (FormatScientific) {
  3040. exp += (NDigits - 1);
  3041. Str.push_back(buffer[NDigits-1]);
  3042. Str.push_back('.');
  3043. if (NDigits == 1)
  3044. Str.push_back('0');
  3045. else
  3046. for (unsigned I = 1; I != NDigits; ++I)
  3047. Str.push_back(buffer[NDigits-1-I]);
  3048. Str.push_back('E');
  3049. Str.push_back(exp >= 0 ? '+' : '-');
  3050. if (exp < 0) exp = -exp;
  3051. SmallVector<char, 6> expbuf;
  3052. do {
  3053. expbuf.push_back((char) ('0' + (exp % 10)));
  3054. exp /= 10;
  3055. } while (exp);
  3056. for (unsigned I = 0, E = expbuf.size(); I != E; ++I)
  3057. Str.push_back(expbuf[E-1-I]);
  3058. return;
  3059. }
  3060. // Non-scientific, positive exponents.
  3061. if (exp >= 0) {
  3062. for (unsigned I = 0; I != NDigits; ++I)
  3063. Str.push_back(buffer[NDigits-1-I]);
  3064. for (unsigned I = 0; I != (unsigned) exp; ++I)
  3065. Str.push_back('0');
  3066. return;
  3067. }
  3068. // Non-scientific, negative exponents.
  3069. // The number of digits to the left of the decimal point.
  3070. int NWholeDigits = exp + (int) NDigits;
  3071. unsigned I = 0;
  3072. if (NWholeDigits > 0) {
  3073. for (; I != (unsigned) NWholeDigits; ++I)
  3074. Str.push_back(buffer[NDigits-I-1]);
  3075. Str.push_back('.');
  3076. } else {
  3077. unsigned NZeros = 1 + (unsigned) -NWholeDigits;
  3078. Str.push_back('0');
  3079. Str.push_back('.');
  3080. for (unsigned Z = 1; Z != NZeros; ++Z)
  3081. Str.push_back('0');
  3082. }
  3083. for (; I != NDigits; ++I)
  3084. Str.push_back(buffer[NDigits-I-1]);
  3085. }
  3086. bool APFloat::getExactInverse(APFloat *inv) const {
  3087. // Special floats and denormals have no exact inverse.
  3088. if (!isFiniteNonZero())
  3089. return false;
  3090. // Check that the number is a power of two by making sure that only the
  3091. // integer bit is set in the significand.
  3092. if (significandLSB() != semantics->precision - 1)
  3093. return false;
  3094. // Get the inverse.
  3095. APFloat reciprocal(*semantics, 1ULL);
  3096. if (reciprocal.divide(*this, rmNearestTiesToEven) != opOK)
  3097. return false;
  3098. // Avoid multiplication with a denormal, it is not safe on all platforms and
  3099. // may be slower than a normal division.
  3100. if (reciprocal.isDenormal())
  3101. return false;
  3102. assert(reciprocal.isFiniteNonZero() &&
  3103. reciprocal.significandLSB() == reciprocal.semantics->precision - 1);
  3104. if (inv)
  3105. *inv = reciprocal;
  3106. return true;
  3107. }
  3108. bool APFloat::isSignaling() const {
  3109. if (!isNaN())
  3110. return false;
  3111. // IEEE-754R 2008 6.2.1: A signaling NaN bit string should be encoded with the
  3112. // first bit of the trailing significand being 0.
  3113. return !APInt::tcExtractBit(significandParts(), semantics->precision - 2);
  3114. }
  3115. /// IEEE-754R 2008 5.3.1: nextUp/nextDown.
  3116. ///
  3117. /// *NOTE* since nextDown(x) = -nextUp(-x), we only implement nextUp with
  3118. /// appropriate sign switching before/after the computation.
  3119. APFloat::opStatus APFloat::next(bool nextDown) {
  3120. // If we are performing nextDown, swap sign so we have -x.
  3121. if (nextDown)
  3122. changeSign();
  3123. // Compute nextUp(x)
  3124. opStatus result = opOK;
  3125. // Handle each float category separately.
  3126. switch (category) {
  3127. case fcInfinity:
  3128. // nextUp(+inf) = +inf
  3129. if (!isNegative())
  3130. break;
  3131. // nextUp(-inf) = -getLargest()
  3132. makeLargest(true);
  3133. break;
  3134. case fcNaN:
  3135. // IEEE-754R 2008 6.2 Par 2: nextUp(sNaN) = qNaN. Set Invalid flag.
  3136. // IEEE-754R 2008 6.2: nextUp(qNaN) = qNaN. Must be identity so we do not
  3137. // change the payload.
  3138. if (isSignaling()) {
  3139. result = opInvalidOp;
  3140. // For consistency, propagate the sign of the sNaN to the qNaN.
  3141. makeNaN(false, isNegative(), 0);
  3142. }
  3143. break;
  3144. case fcZero:
  3145. // nextUp(pm 0) = +getSmallest()
  3146. makeSmallest(false);
  3147. break;
  3148. case fcNormal:
  3149. // nextUp(-getSmallest()) = -0
  3150. if (isSmallest() && isNegative()) {
  3151. APInt::tcSet(significandParts(), 0, partCount());
  3152. category = fcZero;
  3153. exponent = 0;
  3154. break;
  3155. }
  3156. // nextUp(getLargest()) == INFINITY
  3157. if (isLargest() && !isNegative()) {
  3158. APInt::tcSet(significandParts(), 0, partCount());
  3159. category = fcInfinity;
  3160. exponent = semantics->maxExponent + 1;
  3161. break;
  3162. }
  3163. // nextUp(normal) == normal + inc.
  3164. if (isNegative()) {
  3165. // If we are negative, we need to decrement the significand.
  3166. // We only cross a binade boundary that requires adjusting the exponent
  3167. // if:
  3168. // 1. exponent != semantics->minExponent. This implies we are not in the
  3169. // smallest binade or are dealing with denormals.
  3170. // 2. Our significand excluding the integral bit is all zeros.
  3171. bool WillCrossBinadeBoundary =
  3172. exponent != semantics->minExponent && isSignificandAllZeros();
  3173. // Decrement the significand.
  3174. //
  3175. // We always do this since:
  3176. // 1. If we are dealing with a non-binade decrement, by definition we
  3177. // just decrement the significand.
  3178. // 2. If we are dealing with a normal -> normal binade decrement, since
  3179. // we have an explicit integral bit the fact that all bits but the
  3180. // integral bit are zero implies that subtracting one will yield a
  3181. // significand with 0 integral bit and 1 in all other spots. Thus we
  3182. // must just adjust the exponent and set the integral bit to 1.
  3183. // 3. If we are dealing with a normal -> denormal binade decrement,
  3184. // since we set the integral bit to 0 when we represent denormals, we
  3185. // just decrement the significand.
  3186. integerPart *Parts = significandParts();
  3187. APInt::tcDecrement(Parts, partCount());
  3188. if (WillCrossBinadeBoundary) {
  3189. // Our result is a normal number. Do the following:
  3190. // 1. Set the integral bit to 1.
  3191. // 2. Decrement the exponent.
  3192. APInt::tcSetBit(Parts, semantics->precision - 1);
  3193. exponent--;
  3194. }
  3195. } else {
  3196. // If we are positive, we need to increment the significand.
  3197. // We only cross a binade boundary that requires adjusting the exponent if
  3198. // the input is not a denormal and all of said input's significand bits
  3199. // are set. If all of said conditions are true: clear the significand, set
  3200. // the integral bit to 1, and increment the exponent. If we have a
  3201. // denormal always increment since moving denormals and the numbers in the
  3202. // smallest normal binade have the same exponent in our representation.
  3203. bool WillCrossBinadeBoundary = !isDenormal() && isSignificandAllOnes();
  3204. if (WillCrossBinadeBoundary) {
  3205. integerPart *Parts = significandParts();
  3206. APInt::tcSet(Parts, 0, partCount());
  3207. APInt::tcSetBit(Parts, semantics->precision - 1);
  3208. assert(exponent != semantics->maxExponent &&
  3209. "We can not increment an exponent beyond the maxExponent allowed"
  3210. " by the given floating point semantics.");
  3211. exponent++;
  3212. } else {
  3213. incrementSignificand();
  3214. }
  3215. }
  3216. break;
  3217. }
  3218. // If we are performing nextDown, swap sign so we have -nextUp(-x)
  3219. if (nextDown)
  3220. changeSign();
  3221. return result;
  3222. }
  3223. void
  3224. APFloat::makeInf(bool Negative) {
  3225. category = fcInfinity;
  3226. sign = Negative;
  3227. exponent = semantics->maxExponent + 1;
  3228. APInt::tcSet(significandParts(), 0, partCount());
  3229. }
  3230. void
  3231. APFloat::makeZero(bool Negative) {
  3232. category = fcZero;
  3233. sign = Negative;
  3234. exponent = semantics->minExponent-1;
  3235. APInt::tcSet(significandParts(), 0, partCount());
  3236. }