2
0

APFloat.cpp 117 KB

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