decBasic.c 157 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910
  1. /* Common base code for the decNumber C Library.
  2. Copyright (C) 2007-2013 Free Software Foundation, Inc.
  3. Contributed by IBM Corporation. Author Mike Cowlishaw.
  4. This file is part of GCC.
  5. GCC is free software; you can redistribute it and/or modify it under
  6. the terms of the GNU General Public License as published by the Free
  7. Software Foundation; either version 3, or (at your option) any later
  8. version.
  9. GCC is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11. FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
  12. for more details.
  13. Under Section 7 of GPL version 3, you are granted additional
  14. permissions described in the GCC Runtime Library Exception, version
  15. 3.1, as published by the Free Software Foundation.
  16. You should have received a copy of the GNU General Public License and
  17. a copy of the GCC Runtime Library Exception along with this program;
  18. see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
  19. <http://www.gnu.org/licenses/>. */
  20. /* ------------------------------------------------------------------ */
  21. /* decBasic.c -- common base code for Basic decimal types */
  22. /* ------------------------------------------------------------------ */
  23. /* This module comprises code that is shared between decDouble and */
  24. /* decQuad (but not decSingle). The main arithmetic operations are */
  25. /* here (Add, Subtract, Multiply, FMA, and Division operators). */
  26. /* */
  27. /* Unlike decNumber, parameterization takes place at compile time */
  28. /* rather than at runtime. The parameters are set in the decDouble.c */
  29. /* (etc.) files, which then include this one to produce the compiled */
  30. /* code. The functions here, therefore, are code shared between */
  31. /* multiple formats. */
  32. /* */
  33. /* This must be included after decCommon.c. */
  34. /* ------------------------------------------------------------------ */
  35. /* Names here refer to decFloat rather than to decDouble, etc., and */
  36. /* the functions are in strict alphabetical order. */
  37. /* The compile-time flags SINGLE, DOUBLE, and QUAD are set up in */
  38. /* decCommon.c */
  39. #if !defined(QUAD)
  40. #error decBasic.c must be included after decCommon.c
  41. #endif
  42. #if SINGLE
  43. #error Routines in decBasic.c are for decDouble and decQuad only
  44. #endif
  45. /* Private constants */
  46. #define DIVIDE 0x80000000 /* Divide operations [as flags] */
  47. #define REMAINDER 0x40000000 /* .. */
  48. #define DIVIDEINT 0x20000000 /* .. */
  49. #define REMNEAR 0x10000000 /* .. */
  50. /* Private functions (local, used only by routines in this module) */
  51. static decFloat *decDivide(decFloat *, const decFloat *,
  52. const decFloat *, decContext *, uInt);
  53. static decFloat *decCanonical(decFloat *, const decFloat *);
  54. static void decFiniteMultiply(bcdnum *, uByte *, const decFloat *,
  55. const decFloat *);
  56. static decFloat *decInfinity(decFloat *, const decFloat *);
  57. static decFloat *decInvalid(decFloat *, decContext *);
  58. static decFloat *decNaNs(decFloat *, const decFloat *, const decFloat *,
  59. decContext *);
  60. static Int decNumCompare(const decFloat *, const decFloat *, Flag);
  61. static decFloat *decToIntegral(decFloat *, const decFloat *, decContext *,
  62. enum rounding, Flag);
  63. static uInt decToInt32(const decFloat *, decContext *, enum rounding,
  64. Flag, Flag);
  65. /* ------------------------------------------------------------------ */
  66. /* decCanonical -- copy a decFloat, making canonical */
  67. /* */
  68. /* result gets the canonicalized df */
  69. /* df is the decFloat to copy and make canonical */
  70. /* returns result */
  71. /* */
  72. /* This is exposed via decFloatCanonical for Double and Quad only. */
  73. /* This works on specials, too; no error or exception is possible. */
  74. /* ------------------------------------------------------------------ */
  75. static decFloat * decCanonical(decFloat *result, const decFloat *df) {
  76. uInt encode, precode, dpd; /* work */
  77. uInt inword, uoff, canon; /* .. */
  78. Int n; /* counter (down) */
  79. if (df!=result) *result=*df; /* effect copy if needed */
  80. if (DFISSPECIAL(result)) {
  81. if (DFISINF(result)) return decInfinity(result, df); /* clean Infinity */
  82. /* is a NaN */
  83. DFWORD(result, 0)&=~ECONNANMASK; /* clear ECON except selector */
  84. if (DFISCCZERO(df)) return result; /* coefficient continuation is 0 */
  85. /* drop through to check payload */
  86. }
  87. /* return quickly if the coefficient continuation is canonical */
  88. { /* declare block */
  89. #if DOUBLE
  90. uInt sourhi=DFWORD(df, 0);
  91. uInt sourlo=DFWORD(df, 1);
  92. if (CANONDPDOFF(sourhi, 8)
  93. && CANONDPDTWO(sourhi, sourlo, 30)
  94. && CANONDPDOFF(sourlo, 20)
  95. && CANONDPDOFF(sourlo, 10)
  96. && CANONDPDOFF(sourlo, 0)) return result;
  97. #elif QUAD
  98. uInt sourhi=DFWORD(df, 0);
  99. uInt sourmh=DFWORD(df, 1);
  100. uInt sourml=DFWORD(df, 2);
  101. uInt sourlo=DFWORD(df, 3);
  102. if (CANONDPDOFF(sourhi, 4)
  103. && CANONDPDTWO(sourhi, sourmh, 26)
  104. && CANONDPDOFF(sourmh, 16)
  105. && CANONDPDOFF(sourmh, 6)
  106. && CANONDPDTWO(sourmh, sourml, 28)
  107. && CANONDPDOFF(sourml, 18)
  108. && CANONDPDOFF(sourml, 8)
  109. && CANONDPDTWO(sourml, sourlo, 30)
  110. && CANONDPDOFF(sourlo, 20)
  111. && CANONDPDOFF(sourlo, 10)
  112. && CANONDPDOFF(sourlo, 0)) return result;
  113. #endif
  114. } /* block */
  115. /* Loop to repair a non-canonical coefficent, as needed */
  116. inword=DECWORDS-1; /* current input word */
  117. uoff=0; /* bit offset of declet */
  118. encode=DFWORD(result, inword);
  119. for (n=DECLETS-1; n>=0; n--) { /* count down declets of 10 bits */
  120. dpd=encode>>uoff;
  121. uoff+=10;
  122. if (uoff>32) { /* crossed uInt boundary */
  123. inword--;
  124. encode=DFWORD(result, inword);
  125. uoff-=32;
  126. dpd|=encode<<(10-uoff); /* get pending bits */
  127. }
  128. dpd&=0x3ff; /* clear uninteresting bits */
  129. if (dpd<0x16e) continue; /* must be canonical */
  130. canon=BIN2DPD[DPD2BIN[dpd]]; /* determine canonical declet */
  131. if (canon==dpd) continue; /* have canonical declet */
  132. /* need to replace declet */
  133. if (uoff>=10) { /* all within current word */
  134. encode&=~(0x3ff<<(uoff-10)); /* clear the 10 bits ready for replace */
  135. encode|=canon<<(uoff-10); /* insert the canonical form */
  136. DFWORD(result, inword)=encode; /* .. and save */
  137. continue;
  138. }
  139. /* straddled words */
  140. precode=DFWORD(result, inword+1); /* get previous */
  141. precode&=0xffffffff>>(10-uoff); /* clear top bits */
  142. DFWORD(result, inword+1)=precode|(canon<<(32-(10-uoff)));
  143. encode&=0xffffffff<<uoff; /* clear bottom bits */
  144. encode|=canon>>(10-uoff); /* insert canonical */
  145. DFWORD(result, inword)=encode; /* .. and save */
  146. } /* n */
  147. return result;
  148. } /* decCanonical */
  149. /* ------------------------------------------------------------------ */
  150. /* decDivide -- divide operations */
  151. /* */
  152. /* result gets the result of dividing dfl by dfr: */
  153. /* dfl is the first decFloat (lhs) */
  154. /* dfr is the second decFloat (rhs) */
  155. /* set is the context */
  156. /* op is the operation selector */
  157. /* returns result */
  158. /* */
  159. /* op is one of DIVIDE, REMAINDER, DIVIDEINT, or REMNEAR. */
  160. /* ------------------------------------------------------------------ */
  161. #define DIVCOUNT 0 /* 1 to instrument subtractions counter */
  162. #define DIVBASE ((uInt)BILLION) /* the base used for divide */
  163. #define DIVOPLEN DECPMAX9 /* operand length ('digits' base 10**9) */
  164. #define DIVACCLEN (DIVOPLEN*3) /* accumulator length (ditto) */
  165. static decFloat * decDivide(decFloat *result, const decFloat *dfl,
  166. const decFloat *dfr, decContext *set, uInt op) {
  167. decFloat quotient; /* for remainders */
  168. bcdnum num; /* for final conversion */
  169. uInt acc[DIVACCLEN]; /* coefficent in base-billion .. */
  170. uInt div[DIVOPLEN]; /* divisor in base-billion .. */
  171. uInt quo[DIVOPLEN+1]; /* quotient in base-billion .. */
  172. uByte bcdacc[(DIVOPLEN+1)*9+2]; /* for quotient in BCD, +1, +1 */
  173. uInt *msua, *msud, *msuq; /* -> msu of acc, div, and quo */
  174. Int divunits, accunits; /* lengths */
  175. Int quodigits; /* digits in quotient */
  176. uInt *lsua, *lsuq; /* -> current acc and quo lsus */
  177. Int length, multiplier; /* work */
  178. uInt carry, sign; /* .. */
  179. uInt *ua, *ud, *uq; /* .. */
  180. uByte *ub; /* .. */
  181. uInt uiwork; /* for macros */
  182. uInt divtop; /* top unit of div adjusted for estimating */
  183. #if DIVCOUNT
  184. static uInt maxcount=0; /* worst-seen subtractions count */
  185. uInt divcount=0; /* subtractions count [this divide] */
  186. #endif
  187. /* calculate sign */
  188. num.sign=(DFWORD(dfl, 0)^DFWORD(dfr, 0)) & DECFLOAT_Sign;
  189. if (DFISSPECIAL(dfl) || DFISSPECIAL(dfr)) { /* either is special? */
  190. /* NaNs are handled as usual */
  191. if (DFISNAN(dfl) || DFISNAN(dfr)) return decNaNs(result, dfl, dfr, set);
  192. /* one or two infinities */
  193. if (DFISINF(dfl)) {
  194. if (DFISINF(dfr)) return decInvalid(result, set); /* Two infinities bad */
  195. if (op&(REMAINDER|REMNEAR)) return decInvalid(result, set); /* as is rem */
  196. /* Infinity/x is infinite and quiet, even if x=0 */
  197. DFWORD(result, 0)=num.sign;
  198. return decInfinity(result, result);
  199. }
  200. /* must be x/Infinity -- remainders are lhs */
  201. if (op&(REMAINDER|REMNEAR)) return decCanonical(result, dfl);
  202. /* divides: return zero with correct sign and exponent depending */
  203. /* on op (Etiny for divide, 0 for divideInt) */
  204. decFloatZero(result);
  205. if (op==DIVIDEINT) DFWORD(result, 0)|=num.sign; /* add sign */
  206. else DFWORD(result, 0)=num.sign; /* zeros the exponent, too */
  207. return result;
  208. }
  209. /* next, handle zero operands (x/0 and 0/x) */
  210. if (DFISZERO(dfr)) { /* x/0 */
  211. if (DFISZERO(dfl)) { /* 0/0 is undefined */
  212. decFloatZero(result);
  213. DFWORD(result, 0)=DECFLOAT_qNaN;
  214. set->status|=DEC_Division_undefined;
  215. return result;
  216. }
  217. if (op&(REMAINDER|REMNEAR)) return decInvalid(result, set); /* bad rem */
  218. set->status|=DEC_Division_by_zero;
  219. DFWORD(result, 0)=num.sign;
  220. return decInfinity(result, result); /* x/0 -> signed Infinity */
  221. }
  222. num.exponent=GETEXPUN(dfl)-GETEXPUN(dfr); /* ideal exponent */
  223. if (DFISZERO(dfl)) { /* 0/x (x!=0) */
  224. /* if divide, result is 0 with ideal exponent; divideInt has */
  225. /* exponent=0, remainders give zero with lower exponent */
  226. if (op&DIVIDEINT) {
  227. decFloatZero(result);
  228. DFWORD(result, 0)|=num.sign; /* add sign */
  229. return result;
  230. }
  231. if (!(op&DIVIDE)) { /* a remainder */
  232. /* exponent is the minimum of the operands */
  233. num.exponent=MINI(GETEXPUN(dfl), GETEXPUN(dfr));
  234. /* if the result is zero the sign shall be sign of dfl */
  235. num.sign=DFWORD(dfl, 0)&DECFLOAT_Sign;
  236. }
  237. bcdacc[0]=0;
  238. num.msd=bcdacc; /* -> 0 */
  239. num.lsd=bcdacc; /* .. */
  240. return decFinalize(result, &num, set); /* [divide may clamp exponent] */
  241. } /* 0/x */
  242. /* [here, both operands are known to be finite and non-zero] */
  243. /* extract the operand coefficents into 'units' which are */
  244. /* base-billion; the lhs is high-aligned in acc and the msu of both */
  245. /* acc and div is at the right-hand end of array (offset length-1); */
  246. /* the quotient can need one more unit than the operands as digits */
  247. /* in it are not necessarily aligned neatly; further, the quotient */
  248. /* may not start accumulating until after the end of the initial */
  249. /* operand in acc if that is small (e.g., 1) so the accumulator */
  250. /* must have at least that number of units extra (at the ls end) */
  251. GETCOEFFBILL(dfl, acc+DIVACCLEN-DIVOPLEN);
  252. GETCOEFFBILL(dfr, div);
  253. /* zero the low uInts of acc */
  254. acc[0]=0;
  255. acc[1]=0;
  256. acc[2]=0;
  257. acc[3]=0;
  258. #if DOUBLE
  259. #if DIVOPLEN!=2
  260. #error Unexpected Double DIVOPLEN
  261. #endif
  262. #elif QUAD
  263. acc[4]=0;
  264. acc[5]=0;
  265. acc[6]=0;
  266. acc[7]=0;
  267. #if DIVOPLEN!=4
  268. #error Unexpected Quad DIVOPLEN
  269. #endif
  270. #endif
  271. /* set msu and lsu pointers */
  272. msua=acc+DIVACCLEN-1; /* [leading zeros removed below] */
  273. msuq=quo+DIVOPLEN;
  274. /*[loop for div will terminate because operands are non-zero] */
  275. for (msud=div+DIVOPLEN-1; *msud==0;) msud--;
  276. /* the initial least-significant unit of acc is set so acc appears */
  277. /* to have the same length as div. */
  278. /* This moves one position towards the least possible for each */
  279. /* iteration */
  280. divunits=(Int)(msud-div+1); /* precalculate */
  281. lsua=msua-divunits+1; /* initial working lsu of acc */
  282. lsuq=msuq; /* and of quo */
  283. /* set up the estimator for the multiplier; this is the msu of div, */
  284. /* plus two bits from the unit below (if any) rounded up by one if */
  285. /* there are any non-zero bits or units below that [the extra two */
  286. /* bits makes for a much better estimate when the top unit is small] */
  287. divtop=*msud<<2;
  288. if (divunits>1) {
  289. uInt *um=msud-1;
  290. uInt d=*um;
  291. if (d>=750000000) {divtop+=3; d-=750000000;}
  292. else if (d>=500000000) {divtop+=2; d-=500000000;}
  293. else if (d>=250000000) {divtop++; d-=250000000;}
  294. if (d) divtop++;
  295. else for (um--; um>=div; um--) if (*um) {
  296. divtop++;
  297. break;
  298. }
  299. } /* >1 unit */
  300. #if DECTRACE
  301. {Int i;
  302. printf("----- div=");
  303. for (i=divunits-1; i>=0; i--) printf("%09ld ", (LI)div[i]);
  304. printf("\n");}
  305. #endif
  306. /* now collect up to DECPMAX+1 digits in the quotient (this may */
  307. /* need OPLEN+1 uInts if unaligned) */
  308. quodigits=0; /* no digits yet */
  309. for (;; lsua--) { /* outer loop -- each input position */
  310. #if DECCHECK
  311. if (lsua<acc) {
  312. printf("Acc underrun...\n");
  313. break;
  314. }
  315. #endif
  316. #if DECTRACE
  317. printf("Outer: quodigits=%ld acc=", (LI)quodigits);
  318. for (ua=msua; ua>=lsua; ua--) printf("%09ld ", (LI)*ua);
  319. printf("\n");
  320. #endif
  321. *lsuq=0; /* default unit result is 0 */
  322. for (;;) { /* inner loop -- calculate quotient unit */
  323. /* strip leading zero units from acc (either there initially or */
  324. /* from subtraction below); this may strip all if exactly 0 */
  325. for (; *msua==0 && msua>=lsua;) msua--;
  326. accunits=(Int)(msua-lsua+1); /* [maybe 0] */
  327. /* subtraction is only necessary and possible if there are as */
  328. /* least as many units remaining in acc for this iteration as */
  329. /* there are in div */
  330. if (accunits<divunits) {
  331. if (accunits==0) msua++; /* restore */
  332. break;
  333. }
  334. /* If acc is longer than div then subtraction is definitely */
  335. /* possible (as msu of both is non-zero), but if they are the */
  336. /* same length a comparison is needed. */
  337. /* If a subtraction is needed then a good estimate of the */
  338. /* multiplier for the subtraction is also needed in order to */
  339. /* minimise the iterations of this inner loop because the */
  340. /* subtractions needed dominate division performance. */
  341. if (accunits==divunits) {
  342. /* compare the high divunits of acc and div: */
  343. /* acc<div: this quotient unit is unchanged; subtraction */
  344. /* will be possible on the next iteration */
  345. /* acc==div: quotient gains 1, set acc=0 */
  346. /* acc>div: subtraction necessary at this position */
  347. for (ud=msud, ua=msua; ud>div; ud--, ua--) if (*ud!=*ua) break;
  348. /* [now at first mismatch or lsu] */
  349. if (*ud>*ua) break; /* next time... */
  350. if (*ud==*ua) { /* all compared equal */
  351. *lsuq+=1; /* increment result */
  352. msua=lsua; /* collapse acc units */
  353. *msua=0; /* .. to a zero */
  354. break;
  355. }
  356. /* subtraction necessary; estimate multiplier [see above] */
  357. /* if both *msud and *msua are small it is cost-effective to */
  358. /* bring in part of the following units (if any) to get a */
  359. /* better estimate (assume some other non-zero in div) */
  360. #define DIVLO 1000000U
  361. #define DIVHI (DIVBASE/DIVLO)
  362. #if DECUSE64
  363. if (divunits>1) {
  364. /* there cannot be a *(msud-2) for DECDOUBLE so next is */
  365. /* an exact calculation unless DECQUAD (which needs to */
  366. /* assume bits out there if divunits>2) */
  367. uLong mul=(uLong)*msua * DIVBASE + *(msua-1);
  368. uLong div=(uLong)*msud * DIVBASE + *(msud-1);
  369. #if QUAD
  370. if (divunits>2) div++;
  371. #endif
  372. mul/=div;
  373. multiplier=(Int)mul;
  374. }
  375. else multiplier=*msua/(*msud);
  376. #else
  377. if (divunits>1 && *msua<DIVLO && *msud<DIVLO) {
  378. multiplier=(*msua*DIVHI + *(msua-1)/DIVLO)
  379. /(*msud*DIVHI + *(msud-1)/DIVLO +1);
  380. }
  381. else multiplier=(*msua<<2)/divtop;
  382. #endif
  383. }
  384. else { /* accunits>divunits */
  385. /* msud is one unit 'lower' than msua, so estimate differently */
  386. #if DECUSE64
  387. uLong mul;
  388. /* as before, bring in extra digits if possible */
  389. if (divunits>1 && *msua<DIVLO && *msud<DIVLO) {
  390. mul=((uLong)*msua * DIVHI * DIVBASE) + *(msua-1) * DIVHI
  391. + *(msua-2)/DIVLO;
  392. mul/=(*msud*DIVHI + *(msud-1)/DIVLO +1);
  393. }
  394. else if (divunits==1) {
  395. mul=(uLong)*msua * DIVBASE + *(msua-1);
  396. mul/=*msud; /* no more to the right */
  397. }
  398. else {
  399. mul=(uLong)(*msua) * (uInt)(DIVBASE<<2)
  400. + (*(msua-1)<<2);
  401. mul/=divtop; /* [divtop already allows for sticky bits] */
  402. }
  403. multiplier=(Int)mul;
  404. #else
  405. multiplier=*msua * ((DIVBASE<<2)/divtop);
  406. #endif
  407. }
  408. if (multiplier==0) multiplier=1; /* marginal case */
  409. *lsuq+=multiplier;
  410. #if DIVCOUNT
  411. /* printf("Multiplier: %ld\n", (LI)multiplier); */
  412. divcount++;
  413. #endif
  414. /* Carry out the subtraction acc-(div*multiplier); for each */
  415. /* unit in div, do the multiply, split to units (see */
  416. /* decFloatMultiply for the algorithm), and subtract from acc */
  417. #define DIVMAGIC 2305843009U /* 2**61/10**9 */
  418. #define DIVSHIFTA 29
  419. #define DIVSHIFTB 32
  420. carry=0;
  421. for (ud=div, ua=lsua; ud<=msud; ud++, ua++) {
  422. uInt lo, hop;
  423. #if DECUSE64
  424. uLong sub=(uLong)multiplier*(*ud)+carry;
  425. if (sub<DIVBASE) {
  426. carry=0;
  427. lo=(uInt)sub;
  428. }
  429. else {
  430. hop=(uInt)(sub>>DIVSHIFTA);
  431. carry=(uInt)(((uLong)hop*DIVMAGIC)>>DIVSHIFTB);
  432. /* the estimate is now in hi; now calculate sub-hi*10**9 */
  433. /* to get the remainder (which will be <DIVBASE)) */
  434. lo=(uInt)sub;
  435. lo-=carry*DIVBASE; /* low word of result */
  436. if (lo>=DIVBASE) {
  437. lo-=DIVBASE; /* correct by +1 */
  438. carry++;
  439. }
  440. }
  441. #else /* 32-bit */
  442. uInt hi;
  443. /* calculate multiplier*(*ud) into hi and lo */
  444. LONGMUL32HI(hi, *ud, multiplier); /* get the high word */
  445. lo=multiplier*(*ud); /* .. and the low */
  446. lo+=carry; /* add the old hi */
  447. carry=hi+(lo<carry); /* .. with any carry */
  448. if (carry || lo>=DIVBASE) { /* split is needed */
  449. hop=(carry<<3)+(lo>>DIVSHIFTA); /* hi:lo/2**29 */
  450. LONGMUL32HI(carry, hop, DIVMAGIC); /* only need the high word */
  451. /* [DIVSHIFTB is 32, so carry can be used directly] */
  452. /* the estimate is now in carry; now calculate hi:lo-est*10**9; */
  453. /* happily the top word of the result is irrelevant because it */
  454. /* will always be zero so this needs only one multiplication */
  455. lo-=(carry*DIVBASE);
  456. /* the correction here will be at most +1; do it */
  457. if (lo>=DIVBASE) {
  458. lo-=DIVBASE;
  459. carry++;
  460. }
  461. }
  462. #endif
  463. if (lo>*ua) { /* borrow needed */
  464. *ua+=DIVBASE;
  465. carry++;
  466. }
  467. *ua-=lo;
  468. } /* ud loop */
  469. if (carry) *ua-=carry; /* accdigits>divdigits [cannot borrow] */
  470. } /* inner loop */
  471. /* the outer loop terminates when there is either an exact result */
  472. /* or enough digits; first update the quotient digit count and */
  473. /* pointer (if any significant digits) */
  474. #if DECTRACE
  475. if (*lsuq || quodigits) printf("*lsuq=%09ld\n", (LI)*lsuq);
  476. #endif
  477. if (quodigits) {
  478. quodigits+=9; /* had leading unit earlier */
  479. lsuq--;
  480. if (quodigits>DECPMAX+1) break; /* have enough */
  481. }
  482. else if (*lsuq) { /* first quotient digits */
  483. const uInt *pow;
  484. for (pow=DECPOWERS; *lsuq>=*pow; pow++) quodigits++;
  485. lsuq--;
  486. /* [cannot have >DECPMAX+1 on first unit] */
  487. }
  488. if (*msua!=0) continue; /* not an exact result */
  489. /* acc is zero iff used all of original units and zero down to lsua */
  490. /* (must also continue to original lsu for correct quotient length) */
  491. if (lsua>acc+DIVACCLEN-DIVOPLEN) continue;
  492. for (; msua>lsua && *msua==0;) msua--;
  493. if (*msua==0 && msua==lsua) break;
  494. } /* outer loop */
  495. /* all of the original operand in acc has been covered at this point */
  496. /* quotient now has at least DECPMAX+2 digits */
  497. /* *msua is now non-0 if inexact and sticky bits */
  498. /* lsuq is one below the last uint of the quotient */
  499. lsuq++; /* set -> true lsu of quo */
  500. if (*msua) *lsuq|=1; /* apply sticky bit */
  501. /* quo now holds the (unrounded) quotient in base-billion; one */
  502. /* base-billion 'digit' per uInt. */
  503. #if DECTRACE
  504. printf("DivQuo:");
  505. for (uq=msuq; uq>=lsuq; uq--) printf(" %09ld", (LI)*uq);
  506. printf("\n");
  507. #endif
  508. /* Now convert to BCD for rounding and cleanup, starting from the */
  509. /* most significant end [offset by one into bcdacc to leave room */
  510. /* for a possible carry digit if rounding for REMNEAR is needed] */
  511. for (uq=msuq, ub=bcdacc+1; uq>=lsuq; uq--, ub+=9) {
  512. uInt top, mid, rem; /* work */
  513. if (*uq==0) { /* no split needed */
  514. UBFROMUI(ub, 0); /* clear 9 BCD8s */
  515. UBFROMUI(ub+4, 0); /* .. */
  516. *(ub+8)=0; /* .. */
  517. continue;
  518. }
  519. /* *uq is non-zero -- split the base-billion digit into */
  520. /* hi, mid, and low three-digits */
  521. #define divsplit9 1000000 /* divisor */
  522. #define divsplit6 1000 /* divisor */
  523. /* The splitting is done by simple divides and remainders, */
  524. /* assuming the compiler will optimize these [GCC does] */
  525. top=*uq/divsplit9;
  526. rem=*uq%divsplit9;
  527. mid=rem/divsplit6;
  528. rem=rem%divsplit6;
  529. /* lay out the nine BCD digits (plus one unwanted byte) */
  530. UBFROMUI(ub, UBTOUI(&BIN2BCD8[top*4]));
  531. UBFROMUI(ub+3, UBTOUI(&BIN2BCD8[mid*4]));
  532. UBFROMUI(ub+6, UBTOUI(&BIN2BCD8[rem*4]));
  533. } /* BCD conversion loop */
  534. ub--; /* -> lsu */
  535. /* complete the bcdnum; quodigits is correct, so the position of */
  536. /* the first non-zero is known */
  537. num.msd=bcdacc+1+(msuq-lsuq+1)*9-quodigits;
  538. num.lsd=ub;
  539. /* make exponent adjustments, etc */
  540. if (lsua<acc+DIVACCLEN-DIVOPLEN) { /* used extra digits */
  541. num.exponent-=(Int)((acc+DIVACCLEN-DIVOPLEN-lsua)*9);
  542. /* if the result was exact then there may be up to 8 extra */
  543. /* trailing zeros in the overflowed quotient final unit */
  544. if (*msua==0) {
  545. for (; *ub==0;) ub--; /* drop zeros */
  546. num.exponent+=(Int)(num.lsd-ub); /* and adjust exponent */
  547. num.lsd=ub;
  548. }
  549. } /* adjustment needed */
  550. #if DIVCOUNT
  551. if (divcount>maxcount) { /* new high-water nark */
  552. maxcount=divcount;
  553. printf("DivNewMaxCount: %ld\n", (LI)maxcount);
  554. }
  555. #endif
  556. if (op&DIVIDE) return decFinalize(result, &num, set); /* all done */
  557. /* Is DIVIDEINT or a remainder; there is more to do -- first form */
  558. /* the integer (this is done 'after the fact', unlike as in */
  559. /* decNumber, so as not to tax DIVIDE) */
  560. /* The first non-zero digit will be in the first 9 digits, known */
  561. /* from quodigits and num.msd, so there is always space for DECPMAX */
  562. /* digits */
  563. length=(Int)(num.lsd-num.msd+1);
  564. /*printf("Length exp: %ld %ld\n", (LI)length, (LI)num.exponent); */
  565. if (length+num.exponent>DECPMAX) { /* cannot fit */
  566. decFloatZero(result);
  567. DFWORD(result, 0)=DECFLOAT_qNaN;
  568. set->status|=DEC_Division_impossible;
  569. return result;
  570. }
  571. if (num.exponent>=0) { /* already an int, or need pad zeros */
  572. for (ub=num.lsd+1; ub<=num.lsd+num.exponent; ub++) *ub=0;
  573. num.lsd+=num.exponent;
  574. }
  575. else { /* too long: round or truncate needed */
  576. Int drop=-num.exponent;
  577. if (!(op&REMNEAR)) { /* simple truncate */
  578. num.lsd-=drop;
  579. if (num.lsd<num.msd) { /* truncated all */
  580. num.lsd=num.msd; /* make 0 */
  581. *num.lsd=0; /* .. [sign still relevant] */
  582. }
  583. }
  584. else { /* round to nearest even [sigh] */
  585. /* round-to-nearest, in-place; msd is at or to right of bcdacc+1 */
  586. /* (this is a special case of Quantize -- q.v. for commentary) */
  587. uByte *roundat; /* -> re-round digit */
  588. uByte reround; /* reround value */
  589. *(num.msd-1)=0; /* in case of left carry, or make 0 */
  590. if (drop<length) roundat=num.lsd-drop+1;
  591. else if (drop==length) roundat=num.msd;
  592. else roundat=num.msd-1; /* [-> 0] */
  593. reround=*roundat;
  594. for (ub=roundat+1; ub<=num.lsd; ub++) {
  595. if (*ub!=0) {
  596. reround=DECSTICKYTAB[reround];
  597. break;
  598. }
  599. } /* check stickies */
  600. if (roundat>num.msd) num.lsd=roundat-1;
  601. else {
  602. num.msd--; /* use the 0 .. */
  603. num.lsd=num.msd; /* .. at the new MSD place */
  604. }
  605. if (reround!=0) { /* discarding non-zero */
  606. uInt bump=0;
  607. /* rounding is DEC_ROUND_HALF_EVEN always */
  608. if (reround>5) bump=1; /* >0.5 goes up */
  609. else if (reround==5) /* exactly 0.5000 .. */
  610. bump=*(num.lsd) & 0x01; /* .. up iff [new] lsd is odd */
  611. if (bump!=0) { /* need increment */
  612. /* increment the coefficient; this might end up with 1000... */
  613. ub=num.lsd;
  614. for (; UBTOUI(ub-3)==0x09090909; ub-=4) UBFROMUI(ub-3, 0);
  615. for (; *ub==9; ub--) *ub=0; /* at most 3 more */
  616. *ub+=1;
  617. if (ub<num.msd) num.msd--; /* carried */
  618. } /* bump needed */
  619. } /* reround!=0 */
  620. } /* remnear */
  621. } /* round or truncate needed */
  622. num.exponent=0; /* all paths */
  623. /*decShowNum(&num, "int"); */
  624. if (op&DIVIDEINT) return decFinalize(result, &num, set); /* all done */
  625. /* Have a remainder to calculate */
  626. decFinalize(&quotient, &num, set); /* lay out the integer so far */
  627. DFWORD(&quotient, 0)^=DECFLOAT_Sign; /* negate it */
  628. sign=DFWORD(dfl, 0); /* save sign of dfl */
  629. decFloatFMA(result, &quotient, dfr, dfl, set);
  630. if (!DFISZERO(result)) return result;
  631. /* if the result is zero the sign shall be sign of dfl */
  632. DFWORD(&quotient, 0)=sign; /* construct decFloat of sign */
  633. return decFloatCopySign(result, result, &quotient);
  634. } /* decDivide */
  635. /* ------------------------------------------------------------------ */
  636. /* decFiniteMultiply -- multiply two finite decFloats */
  637. /* */
  638. /* num gets the result of multiplying dfl and dfr */
  639. /* bcdacc .. with the coefficient in this array */
  640. /* dfl is the first decFloat (lhs) */
  641. /* dfr is the second decFloat (rhs) */
  642. /* */
  643. /* This effects the multiplication of two decFloats, both known to be */
  644. /* finite, leaving the result in a bcdnum ready for decFinalize (for */
  645. /* use in Multiply) or in a following addition (FMA). */
  646. /* */
  647. /* bcdacc must have space for at least DECPMAX9*18+1 bytes. */
  648. /* No error is possible and no status is set. */
  649. /* ------------------------------------------------------------------ */
  650. /* This routine has two separate implementations of the core */
  651. /* multiplication; both using base-billion. One uses only 32-bit */
  652. /* variables (Ints and uInts) or smaller; the other uses uLongs (for */
  653. /* multiplication and addition only). Both implementations cover */
  654. /* both arithmetic sizes (DOUBLE and QUAD) in order to allow timing */
  655. /* comparisons. In any one compilation only one implementation for */
  656. /* each size can be used, and if DECUSE64 is 0 then use of the 32-bit */
  657. /* version is forced. */
  658. /* */
  659. /* Historical note: an earlier version of this code also supported the */
  660. /* 256-bit format and has been preserved. That is somewhat trickier */
  661. /* during lazy carry splitting because the initial quotient estimate */
  662. /* (est) can exceed 32 bits. */
  663. #define MULTBASE ((uInt)BILLION) /* the base used for multiply */
  664. #define MULOPLEN DECPMAX9 /* operand length ('digits' base 10**9) */
  665. #define MULACCLEN (MULOPLEN*2) /* accumulator length (ditto) */
  666. #define LEADZEROS (MULACCLEN*9 - DECPMAX*2) /* leading zeros always */
  667. /* Assertions: exponent not too large and MULACCLEN is a multiple of 4 */
  668. #if DECEMAXD>9
  669. #error Exponent may overflow when doubled for Multiply
  670. #endif
  671. #if MULACCLEN!=(MULACCLEN/4)*4
  672. /* This assumption is used below only for initialization */
  673. #error MULACCLEN is not a multiple of 4
  674. #endif
  675. static void decFiniteMultiply(bcdnum *num, uByte *bcdacc,
  676. const decFloat *dfl, const decFloat *dfr) {
  677. uInt bufl[MULOPLEN]; /* left coefficient (base-billion) */
  678. uInt bufr[MULOPLEN]; /* right coefficient (base-billion) */
  679. uInt *ui, *uj; /* work */
  680. uByte *ub; /* .. */
  681. uInt uiwork; /* for macros */
  682. #if DECUSE64
  683. uLong accl[MULACCLEN]; /* lazy accumulator (base-billion+) */
  684. uLong *pl; /* work -> lazy accumulator */
  685. uInt acc[MULACCLEN]; /* coefficent in base-billion .. */
  686. #else
  687. uInt acc[MULACCLEN*2]; /* accumulator in base-billion .. */
  688. #endif
  689. uInt *pa; /* work -> accumulator */
  690. /*printf("Base10**9: OpLen=%d MulAcclen=%d\n", OPLEN, MULACCLEN); */
  691. /* Calculate sign and exponent */
  692. num->sign=(DFWORD(dfl, 0)^DFWORD(dfr, 0)) & DECFLOAT_Sign;
  693. num->exponent=GETEXPUN(dfl)+GETEXPUN(dfr); /* [see assertion above] */
  694. /* Extract the coefficients and prepare the accumulator */
  695. /* the coefficients of the operands are decoded into base-billion */
  696. /* numbers in uInt arrays (bufl and bufr, LSD at offset 0) of the */
  697. /* appropriate size. */
  698. GETCOEFFBILL(dfl, bufl);
  699. GETCOEFFBILL(dfr, bufr);
  700. #if DECTRACE && 0
  701. printf("CoeffbL:");
  702. for (ui=bufl+MULOPLEN-1; ui>=bufl; ui--) printf(" %08lx", (LI)*ui);
  703. printf("\n");
  704. printf("CoeffbR:");
  705. for (uj=bufr+MULOPLEN-1; uj>=bufr; uj--) printf(" %08lx", (LI)*uj);
  706. printf("\n");
  707. #endif
  708. /* start the 64-bit/32-bit differing paths... */
  709. #if DECUSE64
  710. /* zero the accumulator */
  711. #if MULACCLEN==4
  712. accl[0]=0; accl[1]=0; accl[2]=0; accl[3]=0;
  713. #else /* use a loop */
  714. /* MULACCLEN is a multiple of four, asserted above */
  715. for (pl=accl; pl<accl+MULACCLEN; pl+=4) {
  716. *pl=0; *(pl+1)=0; *(pl+2)=0; *(pl+3)=0;/* [reduce overhead] */
  717. } /* pl */
  718. #endif
  719. /* Effect the multiplication */
  720. /* The multiplcation proceeds using MFC's lazy-carry resolution */
  721. /* algorithm from decNumber. First, the multiplication is */
  722. /* effected, allowing accumulation of the partial products (which */
  723. /* are in base-billion at each column position) into 64 bits */
  724. /* without resolving back to base=billion after each addition. */
  725. /* These 64-bit numbers (which may contain up to 19 decimal digits) */
  726. /* are then split using the Clark & Cowlishaw algorithm (see below). */
  727. /* [Testing for 0 in the inner loop is not really a 'win'] */
  728. for (ui=bufr; ui<bufr+MULOPLEN; ui++) { /* over each item in rhs */
  729. if (*ui==0) continue; /* product cannot affect result */
  730. pl=accl+(ui-bufr); /* where to add the lhs */
  731. for (uj=bufl; uj<bufl+MULOPLEN; uj++, pl++) { /* over each item in lhs */
  732. /* if (*uj==0) continue; // product cannot affect result */
  733. *pl+=((uLong)*ui)*(*uj);
  734. } /* uj */
  735. } /* ui */
  736. /* The 64-bit carries must now be resolved; this means that a */
  737. /* quotient/remainder has to be calculated for base-billion (1E+9). */
  738. /* For this, Clark & Cowlishaw's quotient estimation approach (also */
  739. /* used in decNumber) is needed, because 64-bit divide is generally */
  740. /* extremely slow on 32-bit machines, and may be slower than this */
  741. /* approach even on 64-bit machines. This algorithm splits X */
  742. /* using: */
  743. /* */
  744. /* magic=2**(A+B)/1E+9; // 'magic number' */
  745. /* hop=X/2**A; // high order part of X (by shift) */
  746. /* est=magic*hop/2**B // quotient estimate (may be low by 1) */
  747. /* */
  748. /* A and B are quite constrained; hop and magic must fit in 32 bits, */
  749. /* and 2**(A+B) must be as large as possible (which is 2**61 if */
  750. /* magic is to fit). Further, maxX increases with the length of */
  751. /* the operands (and hence the number of partial products */
  752. /* accumulated); maxX is OPLEN*(10**18), which is up to 19 digits. */
  753. /* */
  754. /* It can be shown that when OPLEN is 2 then the maximum error in */
  755. /* the estimated quotient is <1, but for larger maximum x the */
  756. /* maximum error is above 1 so a correction that is >1 may be */
  757. /* needed. Values of A and B are chosen to satisfy the constraints */
  758. /* just mentioned while minimizing the maximum error (and hence the */
  759. /* maximum correction), as shown in the following table: */
  760. /* */
  761. /* Type OPLEN A B maxX maxError maxCorrection */
  762. /* --------------------------------------------------------- */
  763. /* DOUBLE 2 29 32 <2*10**18 0.63 1 */
  764. /* QUAD 4 30 31 <4*10**18 1.17 2 */
  765. /* */
  766. /* In the OPLEN==2 case there is most choice, but the value for B */
  767. /* of 32 has a big advantage as then the calculation of the */
  768. /* estimate requires no shifting; the compiler can extract the high */
  769. /* word directly after multiplying magic*hop. */
  770. #define MULMAGIC 2305843009U /* 2**61/10**9 [both cases] */
  771. #if DOUBLE
  772. #define MULSHIFTA 29
  773. #define MULSHIFTB 32
  774. #elif QUAD
  775. #define MULSHIFTA 30
  776. #define MULSHIFTB 31
  777. #else
  778. #error Unexpected type
  779. #endif
  780. #if DECTRACE
  781. printf("MulAccl:");
  782. for (pl=accl+MULACCLEN-1; pl>=accl; pl--)
  783. printf(" %08lx:%08lx", (LI)(*pl>>32), (LI)(*pl&0xffffffff));
  784. printf("\n");
  785. #endif
  786. for (pl=accl, pa=acc; pl<accl+MULACCLEN; pl++, pa++) { /* each column position */
  787. uInt lo, hop; /* work */
  788. uInt est; /* cannot exceed 4E+9 */
  789. if (*pl>=MULTBASE) {
  790. /* *pl holds a binary number which needs to be split */
  791. hop=(uInt)(*pl>>MULSHIFTA);
  792. est=(uInt)(((uLong)hop*MULMAGIC)>>MULSHIFTB);
  793. /* the estimate is now in est; now calculate hi:lo-est*10**9; */
  794. /* happily the top word of the result is irrelevant because it */
  795. /* will always be zero so this needs only one multiplication */
  796. lo=(uInt)(*pl-((uLong)est*MULTBASE)); /* low word of result */
  797. /* If QUAD, the correction here could be +2 */
  798. if (lo>=MULTBASE) {
  799. lo-=MULTBASE; /* correct by +1 */
  800. est++;
  801. #if QUAD
  802. /* may need to correct by +2 */
  803. if (lo>=MULTBASE) {
  804. lo-=MULTBASE;
  805. est++;
  806. }
  807. #endif
  808. }
  809. /* finally place lo as the new coefficient 'digit' and add est to */
  810. /* the next place up [this is safe because this path is never */
  811. /* taken on the final iteration as *pl will fit] */
  812. *pa=lo;
  813. *(pl+1)+=est;
  814. } /* *pl needed split */
  815. else { /* *pl<MULTBASE */
  816. *pa=(uInt)*pl; /* just copy across */
  817. }
  818. } /* pl loop */
  819. #else /* 32-bit */
  820. for (pa=acc;; pa+=4) { /* zero the accumulator */
  821. *pa=0; *(pa+1)=0; *(pa+2)=0; *(pa+3)=0; /* [reduce overhead] */
  822. if (pa==acc+MULACCLEN*2-4) break; /* multiple of 4 asserted */
  823. } /* pa */
  824. /* Effect the multiplication */
  825. /* uLongs are not available (and in particular, there is no uLong */
  826. /* divide) but it is still possible to use MFC's lazy-carry */
  827. /* resolution algorithm from decNumber. First, the multiplication */
  828. /* is effected, allowing accumulation of the partial products */
  829. /* (which are in base-billion at each column position) into 64 bits */
  830. /* [with the high-order 32 bits in each position being held at */
  831. /* offset +ACCLEN from the low-order 32 bits in the accumulator]. */
  832. /* These 64-bit numbers (which may contain up to 19 decimal digits) */
  833. /* are then split using the Clark & Cowlishaw algorithm (see */
  834. /* below). */
  835. for (ui=bufr;; ui++) { /* over each item in rhs */
  836. uInt hi, lo; /* words of exact multiply result */
  837. pa=acc+(ui-bufr); /* where to add the lhs */
  838. for (uj=bufl;; uj++, pa++) { /* over each item in lhs */
  839. LONGMUL32HI(hi, *ui, *uj); /* calculate product of digits */
  840. lo=(*ui)*(*uj); /* .. */
  841. *pa+=lo; /* accumulate low bits and .. */
  842. *(pa+MULACCLEN)+=hi+(*pa<lo); /* .. high bits with any carry */
  843. if (uj==bufl+MULOPLEN-1) break;
  844. }
  845. if (ui==bufr+MULOPLEN-1) break;
  846. }
  847. /* The 64-bit carries must now be resolved; this means that a */
  848. /* quotient/remainder has to be calculated for base-billion (1E+9). */
  849. /* For this, Clark & Cowlishaw's quotient estimation approach (also */
  850. /* used in decNumber) is needed, because 64-bit divide is generally */
  851. /* extremely slow on 32-bit machines. This algorithm splits X */
  852. /* using: */
  853. /* */
  854. /* magic=2**(A+B)/1E+9; // 'magic number' */
  855. /* hop=X/2**A; // high order part of X (by shift) */
  856. /* est=magic*hop/2**B // quotient estimate (may be low by 1) */
  857. /* */
  858. /* A and B are quite constrained; hop and magic must fit in 32 bits, */
  859. /* and 2**(A+B) must be as large as possible (which is 2**61 if */
  860. /* magic is to fit). Further, maxX increases with the length of */
  861. /* the operands (and hence the number of partial products */
  862. /* accumulated); maxX is OPLEN*(10**18), which is up to 19 digits. */
  863. /* */
  864. /* It can be shown that when OPLEN is 2 then the maximum error in */
  865. /* the estimated quotient is <1, but for larger maximum x the */
  866. /* maximum error is above 1 so a correction that is >1 may be */
  867. /* needed. Values of A and B are chosen to satisfy the constraints */
  868. /* just mentioned while minimizing the maximum error (and hence the */
  869. /* maximum correction), as shown in the following table: */
  870. /* */
  871. /* Type OPLEN A B maxX maxError maxCorrection */
  872. /* --------------------------------------------------------- */
  873. /* DOUBLE 2 29 32 <2*10**18 0.63 1 */
  874. /* QUAD 4 30 31 <4*10**18 1.17 2 */
  875. /* */
  876. /* In the OPLEN==2 case there is most choice, but the value for B */
  877. /* of 32 has a big advantage as then the calculation of the */
  878. /* estimate requires no shifting; the high word is simply */
  879. /* calculated from multiplying magic*hop. */
  880. #define MULMAGIC 2305843009U /* 2**61/10**9 [both cases] */
  881. #if DOUBLE
  882. #define MULSHIFTA 29
  883. #define MULSHIFTB 32
  884. #elif QUAD
  885. #define MULSHIFTA 30
  886. #define MULSHIFTB 31
  887. #else
  888. #error Unexpected type
  889. #endif
  890. #if DECTRACE
  891. printf("MulHiLo:");
  892. for (pa=acc+MULACCLEN-1; pa>=acc; pa--)
  893. printf(" %08lx:%08lx", (LI)*(pa+MULACCLEN), (LI)*pa);
  894. printf("\n");
  895. #endif
  896. for (pa=acc;; pa++) { /* each low uInt */
  897. uInt hi, lo; /* words of exact multiply result */
  898. uInt hop, estlo; /* work */
  899. #if QUAD
  900. uInt esthi; /* .. */
  901. #endif
  902. lo=*pa;
  903. hi=*(pa+MULACCLEN); /* top 32 bits */
  904. /* hi and lo now hold a binary number which needs to be split */
  905. #if DOUBLE
  906. hop=(hi<<3)+(lo>>MULSHIFTA); /* hi:lo/2**29 */
  907. LONGMUL32HI(estlo, hop, MULMAGIC);/* only need the high word */
  908. /* [MULSHIFTB is 32, so estlo can be used directly] */
  909. /* the estimate is now in estlo; now calculate hi:lo-est*10**9; */
  910. /* happily the top word of the result is irrelevant because it */
  911. /* will always be zero so this needs only one multiplication */
  912. lo-=(estlo*MULTBASE);
  913. /* esthi=0; // high word is ignored below */
  914. /* the correction here will be at most +1; do it */
  915. if (lo>=MULTBASE) {
  916. lo-=MULTBASE;
  917. estlo++;
  918. }
  919. #elif QUAD
  920. hop=(hi<<2)+(lo>>MULSHIFTA); /* hi:lo/2**30 */
  921. LONGMUL32HI(esthi, hop, MULMAGIC);/* shift will be 31 .. */
  922. estlo=hop*MULMAGIC; /* .. so low word needed */
  923. estlo=(esthi<<1)+(estlo>>MULSHIFTB); /* [just the top bit] */
  924. /* esthi=0; // high word is ignored below */
  925. lo-=(estlo*MULTBASE); /* as above */
  926. /* the correction here could be +1 or +2 */
  927. if (lo>=MULTBASE) {
  928. lo-=MULTBASE;
  929. estlo++;
  930. }
  931. if (lo>=MULTBASE) {
  932. lo-=MULTBASE;
  933. estlo++;
  934. }
  935. #else
  936. #error Unexpected type
  937. #endif
  938. /* finally place lo as the new accumulator digit and add est to */
  939. /* the next place up; this latter add could cause a carry of 1 */
  940. /* to the high word of the next place */
  941. *pa=lo;
  942. *(pa+1)+=estlo;
  943. /* esthi is always 0 for DOUBLE and QUAD so this is skipped */
  944. /* *(pa+1+MULACCLEN)+=esthi; */
  945. if (*(pa+1)<estlo) *(pa+1+MULACCLEN)+=1; /* carry */
  946. if (pa==acc+MULACCLEN-2) break; /* [MULACCLEN-1 will never need split] */
  947. } /* pa loop */
  948. #endif
  949. /* At this point, whether using the 64-bit or the 32-bit paths, the */
  950. /* accumulator now holds the (unrounded) result in base-billion; */
  951. /* one base-billion 'digit' per uInt. */
  952. #if DECTRACE
  953. printf("MultAcc:");
  954. for (pa=acc+MULACCLEN-1; pa>=acc; pa--) printf(" %09ld", (LI)*pa);
  955. printf("\n");
  956. #endif
  957. /* Now convert to BCD for rounding and cleanup, starting from the */
  958. /* most significant end */
  959. pa=acc+MULACCLEN-1;
  960. if (*pa!=0) num->msd=bcdacc+LEADZEROS;/* drop known lead zeros */
  961. else { /* >=1 word of leading zeros */
  962. num->msd=bcdacc; /* known leading zeros are gone */
  963. pa--; /* skip first word .. */
  964. for (; *pa==0; pa--) if (pa==acc) break; /* .. and any more leading 0s */
  965. }
  966. for (ub=bcdacc;; pa--, ub+=9) {
  967. if (*pa!=0) { /* split(s) needed */
  968. uInt top, mid, rem; /* work */
  969. /* *pa is non-zero -- split the base-billion acc digit into */
  970. /* hi, mid, and low three-digits */
  971. #define mulsplit9 1000000 /* divisor */
  972. #define mulsplit6 1000 /* divisor */
  973. /* The splitting is done by simple divides and remainders, */
  974. /* assuming the compiler will optimize these where useful */
  975. /* [GCC does] */
  976. top=*pa/mulsplit9;
  977. rem=*pa%mulsplit9;
  978. mid=rem/mulsplit6;
  979. rem=rem%mulsplit6;
  980. /* lay out the nine BCD digits (plus one unwanted byte) */
  981. UBFROMUI(ub, UBTOUI(&BIN2BCD8[top*4]));
  982. UBFROMUI(ub+3, UBTOUI(&BIN2BCD8[mid*4]));
  983. UBFROMUI(ub+6, UBTOUI(&BIN2BCD8[rem*4]));
  984. }
  985. else { /* *pa==0 */
  986. UBFROMUI(ub, 0); /* clear 9 BCD8s */
  987. UBFROMUI(ub+4, 0); /* .. */
  988. *(ub+8)=0; /* .. */
  989. }
  990. if (pa==acc) break;
  991. } /* BCD conversion loop */
  992. num->lsd=ub+8; /* complete the bcdnum .. */
  993. #if DECTRACE
  994. decShowNum(num, "postmult");
  995. decFloatShow(dfl, "dfl");
  996. decFloatShow(dfr, "dfr");
  997. #endif
  998. return;
  999. } /* decFiniteMultiply */
  1000. /* ------------------------------------------------------------------ */
  1001. /* decFloatAbs -- absolute value, heeding NaNs, etc. */
  1002. /* */
  1003. /* result gets the canonicalized df with sign 0 */
  1004. /* df is the decFloat to abs */
  1005. /* set is the context */
  1006. /* returns result */
  1007. /* */
  1008. /* This has the same effect as decFloatPlus unless df is negative, */
  1009. /* in which case it has the same effect as decFloatMinus. The */
  1010. /* effect is also the same as decFloatCopyAbs except that NaNs are */
  1011. /* handled normally (the sign of a NaN is not affected, and an sNaN */
  1012. /* will signal) and the result will be canonical. */
  1013. /* ------------------------------------------------------------------ */
  1014. decFloat * decFloatAbs(decFloat *result, const decFloat *df,
  1015. decContext *set) {
  1016. if (DFISNAN(df)) return decNaNs(result, df, NULL, set);
  1017. decCanonical(result, df); /* copy and check */
  1018. DFBYTE(result, 0)&=~0x80; /* zero sign bit */
  1019. return result;
  1020. } /* decFloatAbs */
  1021. /* ------------------------------------------------------------------ */
  1022. /* decFloatAdd -- add two decFloats */
  1023. /* */
  1024. /* result gets the result of adding dfl and dfr: */
  1025. /* dfl is the first decFloat (lhs) */
  1026. /* dfr is the second decFloat (rhs) */
  1027. /* set is the context */
  1028. /* returns result */
  1029. /* */
  1030. /* ------------------------------------------------------------------ */
  1031. #if QUAD
  1032. /* Table for testing MSDs for fastpath elimination; returns the MSD of */
  1033. /* a decDouble or decQuad (top 6 bits tested) ignoring the sign. */
  1034. /* Infinities return -32 and NaNs return -128 so that summing the two */
  1035. /* MSDs also allows rapid tests for the Specials (see code below). */
  1036. const Int DECTESTMSD[64]={
  1037. 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7,
  1038. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 9, 8, 9, -32, -128,
  1039. 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7,
  1040. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 9, 8, 9, -32, -128};
  1041. #else
  1042. /* The table for testing MSDs is shared between the modules */
  1043. extern const Int DECTESTMSD[64];
  1044. #endif
  1045. decFloat * decFloatAdd(decFloat *result,
  1046. const decFloat *dfl, const decFloat *dfr,
  1047. decContext *set) {
  1048. bcdnum num; /* for final conversion */
  1049. Int bexpl, bexpr; /* left and right biased exponents */
  1050. uByte *ub, *us, *ut; /* work */
  1051. uInt uiwork; /* for macros */
  1052. #if QUAD
  1053. uShort uswork; /* .. */
  1054. #endif
  1055. uInt sourhil, sourhir; /* top words from source decFloats */
  1056. /* [valid only through end of */
  1057. /* fastpath code -- before swap] */
  1058. uInt diffsign; /* non-zero if signs differ */
  1059. uInt carry; /* carry: 0 or 1 before add loop */
  1060. Int overlap; /* coefficient overlap (if full) */
  1061. Int summ; /* sum of the MSDs */
  1062. /* the following buffers hold coefficients with various alignments */
  1063. /* (see commentary and diagrams below) */
  1064. uByte acc[4+2+DECPMAX*3+8];
  1065. uByte buf[4+2+DECPMAX*2];
  1066. uByte *umsd, *ulsd; /* local MSD and LSD pointers */
  1067. #if DECLITEND
  1068. #define CARRYPAT 0x01000000 /* carry=1 pattern */
  1069. #else
  1070. #define CARRYPAT 0x00000001 /* carry=1 pattern */
  1071. #endif
  1072. /* Start decoding the arguments */
  1073. /* The initial exponents are placed into the opposite Ints to */
  1074. /* that which might be expected; there are two sets of data to */
  1075. /* keep track of (each decFloat and the corresponding exponent), */
  1076. /* and this scheme means that at the swap point (after comparing */
  1077. /* exponents) only one pair of words needs to be swapped */
  1078. /* whichever path is taken (thereby minimising worst-case path). */
  1079. /* The calculated exponents will be nonsense when the arguments are */
  1080. /* Special, but are not used in that path */
  1081. sourhil=DFWORD(dfl, 0); /* LHS top word */
  1082. summ=DECTESTMSD[sourhil>>26]; /* get first MSD for testing */
  1083. bexpr=DECCOMBEXP[sourhil>>26]; /* get exponent high bits (in place) */
  1084. bexpr+=GETECON(dfl); /* .. + continuation */
  1085. sourhir=DFWORD(dfr, 0); /* RHS top word */
  1086. summ+=DECTESTMSD[sourhir>>26]; /* sum MSDs for testing */
  1087. bexpl=DECCOMBEXP[sourhir>>26];
  1088. bexpl+=GETECON(dfr);
  1089. /* here bexpr has biased exponent from lhs, and vice versa */
  1090. diffsign=(sourhil^sourhir)&DECFLOAT_Sign;
  1091. /* now determine whether to take a fast path or the full-function */
  1092. /* slow path. The slow path must be taken when: */
  1093. /* -- both numbers are finite, and: */
  1094. /* the exponents are different, or */
  1095. /* the signs are different, or */
  1096. /* the sum of the MSDs is >8 (hence might overflow) */
  1097. /* specialness and the sum of the MSDs can be tested at once using */
  1098. /* the summ value just calculated, so the test for specials is no */
  1099. /* longer on the worst-case path (as of 3.60) */
  1100. if (summ<=8) { /* MSD+MSD is good, or there is a special */
  1101. if (summ<0) { /* there is a special */
  1102. /* Inf+Inf would give -64; Inf+finite is -32 or higher */
  1103. if (summ<-64) return decNaNs(result, dfl, dfr, set); /* one or two NaNs */
  1104. /* two infinities with different signs is invalid */
  1105. if (summ==-64 && diffsign) return decInvalid(result, set);
  1106. if (DFISINF(dfl)) return decInfinity(result, dfl); /* LHS is infinite */
  1107. return decInfinity(result, dfr); /* RHS must be Inf */
  1108. }
  1109. /* Here when both arguments are finite; fast path is possible */
  1110. /* (currently only for aligned and same-sign) */
  1111. if (bexpr==bexpl && !diffsign) {
  1112. uInt tac[DECLETS+1]; /* base-1000 coefficient */
  1113. uInt encode; /* work */
  1114. /* Get one coefficient as base-1000 and add the other */
  1115. GETCOEFFTHOU(dfl, tac); /* least-significant goes to [0] */
  1116. ADDCOEFFTHOU(dfr, tac);
  1117. /* here the sum of the MSDs (plus any carry) will be <10 due to */
  1118. /* the fastpath test earlier */
  1119. /* construct the result; low word is the same for both formats */
  1120. encode =BIN2DPD[tac[0]];
  1121. encode|=BIN2DPD[tac[1]]<<10;
  1122. encode|=BIN2DPD[tac[2]]<<20;
  1123. encode|=BIN2DPD[tac[3]]<<30;
  1124. DFWORD(result, (DECBYTES/4)-1)=encode;
  1125. /* collect next two declets (all that remains, for Double) */
  1126. encode =BIN2DPD[tac[3]]>>2;
  1127. encode|=BIN2DPD[tac[4]]<<8;
  1128. #if QUAD
  1129. /* complete and lay out middling words */
  1130. encode|=BIN2DPD[tac[5]]<<18;
  1131. encode|=BIN2DPD[tac[6]]<<28;
  1132. DFWORD(result, 2)=encode;
  1133. encode =BIN2DPD[tac[6]]>>4;
  1134. encode|=BIN2DPD[tac[7]]<<6;
  1135. encode|=BIN2DPD[tac[8]]<<16;
  1136. encode|=BIN2DPD[tac[9]]<<26;
  1137. DFWORD(result, 1)=encode;
  1138. /* and final two declets */
  1139. encode =BIN2DPD[tac[9]]>>6;
  1140. encode|=BIN2DPD[tac[10]]<<4;
  1141. #endif
  1142. /* add exponent continuation and sign (from either argument) */
  1143. encode|=sourhil & (ECONMASK | DECFLOAT_Sign);
  1144. /* create lookup index = MSD + top two bits of biased exponent <<4 */
  1145. tac[DECLETS]|=(bexpl>>DECECONL)<<4;
  1146. encode|=DECCOMBFROM[tac[DECLETS]]; /* add constructed combination field */
  1147. DFWORD(result, 0)=encode; /* complete */
  1148. /* decFloatShow(result, ">"); */
  1149. return result;
  1150. } /* fast path OK */
  1151. /* drop through to slow path */
  1152. } /* low sum or Special(s) */
  1153. /* Slow path required -- arguments are finite and might overflow, */
  1154. /* or require alignment, or might have different signs */
  1155. /* now swap either exponents or argument pointers */
  1156. if (bexpl<=bexpr) {
  1157. /* original left is bigger */
  1158. Int bexpswap=bexpl;
  1159. bexpl=bexpr;
  1160. bexpr=bexpswap;
  1161. /* printf("left bigger\n"); */
  1162. }
  1163. else {
  1164. const decFloat *dfswap=dfl;
  1165. dfl=dfr;
  1166. dfr=dfswap;
  1167. /* printf("right bigger\n"); */
  1168. }
  1169. /* [here dfl and bexpl refer to the datum with the larger exponent, */
  1170. /* of if the exponents are equal then the original LHS argument] */
  1171. /* if lhs is zero then result will be the rhs (now known to have */
  1172. /* the smaller exponent), which also may need to be tested for zero */
  1173. /* for the weird IEEE 754 sign rules */
  1174. if (DFISZERO(dfl)) {
  1175. decCanonical(result, dfr); /* clean copy */
  1176. /* "When the sum of two operands with opposite signs is */
  1177. /* exactly zero, the sign of that sum shall be '+' in all */
  1178. /* rounding modes except round toward -Infinity, in which */
  1179. /* mode that sign shall be '-'." */
  1180. if (diffsign && DFISZERO(result)) {
  1181. DFWORD(result, 0)&=~DECFLOAT_Sign; /* assume sign 0 */
  1182. if (set->round==DEC_ROUND_FLOOR) DFWORD(result, 0)|=DECFLOAT_Sign;
  1183. }
  1184. return result;
  1185. } /* numfl is zero */
  1186. /* [here, LHS is non-zero; code below assumes that] */
  1187. /* Coefficients layout during the calculations to follow: */
  1188. /* */
  1189. /* Overlap case: */
  1190. /* +------------------------------------------------+ */
  1191. /* acc: |0000| coeffa | tail B | | */
  1192. /* +------------------------------------------------+ */
  1193. /* buf: |0000| pad0s | coeffb | | */
  1194. /* +------------------------------------------------+ */
  1195. /* */
  1196. /* Touching coefficients or gap: */
  1197. /* +------------------------------------------------+ */
  1198. /* acc: |0000| coeffa | gap | coeffb | */
  1199. /* +------------------------------------------------+ */
  1200. /* [buf not used or needed; gap clamped to Pmax] */
  1201. /* lay out lhs coefficient into accumulator; this starts at acc+4 */
  1202. /* for decDouble or acc+6 for decQuad so the LSD is word- */
  1203. /* aligned; the top word gap is there only in case a carry digit */
  1204. /* is prefixed after the add -- it does not need to be zeroed */
  1205. #if DOUBLE
  1206. #define COFF 4 /* offset into acc */
  1207. #elif QUAD
  1208. UBFROMUS(acc+4, 0); /* prefix 00 */
  1209. #define COFF 6 /* offset into acc */
  1210. #endif
  1211. GETCOEFF(dfl, acc+COFF); /* decode from decFloat */
  1212. ulsd=acc+COFF+DECPMAX-1;
  1213. umsd=acc+4; /* [having this here avoids */
  1214. #if DECTRACE
  1215. {bcdnum tum;
  1216. tum.msd=umsd;
  1217. tum.lsd=ulsd;
  1218. tum.exponent=bexpl-DECBIAS;
  1219. tum.sign=DFWORD(dfl, 0) & DECFLOAT_Sign;
  1220. decShowNum(&tum, "dflx");}
  1221. #endif
  1222. /* if signs differ, take ten's complement of lhs (here the */
  1223. /* coefficient is subtracted from all-nines; the 1 is added during */
  1224. /* the later add cycle -- zeros to the right do not matter because */
  1225. /* the complement of zero is zero); these are fixed-length inverts */
  1226. /* where the lsd is known to be at a 4-byte boundary (so no borrow */
  1227. /* possible) */
  1228. carry=0; /* assume no carry */
  1229. if (diffsign) {
  1230. carry=CARRYPAT; /* for +1 during add */
  1231. UBFROMUI(acc+ 4, 0x09090909-UBTOUI(acc+ 4));
  1232. UBFROMUI(acc+ 8, 0x09090909-UBTOUI(acc+ 8));
  1233. UBFROMUI(acc+12, 0x09090909-UBTOUI(acc+12));
  1234. UBFROMUI(acc+16, 0x09090909-UBTOUI(acc+16));
  1235. #if QUAD
  1236. UBFROMUI(acc+20, 0x09090909-UBTOUI(acc+20));
  1237. UBFROMUI(acc+24, 0x09090909-UBTOUI(acc+24));
  1238. UBFROMUI(acc+28, 0x09090909-UBTOUI(acc+28));
  1239. UBFROMUI(acc+32, 0x09090909-UBTOUI(acc+32));
  1240. UBFROMUI(acc+36, 0x09090909-UBTOUI(acc+36));
  1241. #endif
  1242. } /* diffsign */
  1243. /* now process the rhs coefficient; if it cannot overlap lhs then */
  1244. /* it can be put straight into acc (with an appropriate gap, if */
  1245. /* needed) because no actual addition will be needed (except */
  1246. /* possibly to complete ten's complement) */
  1247. overlap=DECPMAX-(bexpl-bexpr);
  1248. #if DECTRACE
  1249. printf("exps: %ld %ld\n", (LI)(bexpl-DECBIAS), (LI)(bexpr-DECBIAS));
  1250. printf("Overlap=%ld carry=%08lx\n", (LI)overlap, (LI)carry);
  1251. #endif
  1252. if (overlap<=0) { /* no overlap possible */
  1253. uInt gap; /* local work */
  1254. /* since a full addition is not needed, a ten's complement */
  1255. /* calculation started above may need to be completed */
  1256. if (carry) {
  1257. for (ub=ulsd; *ub==9; ub--) *ub=0;
  1258. *ub+=1;
  1259. carry=0; /* taken care of */
  1260. }
  1261. /* up to DECPMAX-1 digits of the final result can extend down */
  1262. /* below the LSD of the lhs, so if the gap is >DECPMAX then the */
  1263. /* rhs will be simply sticky bits. In this case the gap is */
  1264. /* clamped to DECPMAX and the exponent adjusted to suit [this is */
  1265. /* safe because the lhs is non-zero]. */
  1266. gap=-overlap;
  1267. if (gap>DECPMAX) {
  1268. bexpr+=gap-1;
  1269. gap=DECPMAX;
  1270. }
  1271. ub=ulsd+gap+1; /* where MSD will go */
  1272. /* Fill the gap with 0s; note that there is no addition to do */
  1273. ut=acc+COFF+DECPMAX; /* start of gap */
  1274. for (; ut<ub; ut+=4) UBFROMUI(ut, 0); /* mind the gap */
  1275. if (overlap<-DECPMAX) { /* gap was > DECPMAX */
  1276. *ub=(uByte)(!DFISZERO(dfr)); /* make sticky digit */
  1277. }
  1278. else { /* need full coefficient */
  1279. GETCOEFF(dfr, ub); /* decode from decFloat */
  1280. ub+=DECPMAX-1; /* new LSD... */
  1281. }
  1282. ulsd=ub; /* save new LSD */
  1283. } /* no overlap possible */
  1284. else { /* overlap>0 */
  1285. /* coefficients overlap (perhaps completely, although also */
  1286. /* perhaps only where zeros) */
  1287. if (overlap==DECPMAX) { /* aligned */
  1288. ub=buf+COFF; /* where msd will go */
  1289. #if QUAD
  1290. UBFROMUS(buf+4, 0); /* clear quad's 00 */
  1291. #endif
  1292. GETCOEFF(dfr, ub); /* decode from decFloat */
  1293. }
  1294. else { /* unaligned */
  1295. ub=buf+COFF+DECPMAX-overlap; /* where MSD will go */
  1296. /* Fill the prefix gap with 0s; 8 will cover most common */
  1297. /* unalignments, so start with direct assignments (a loop is */
  1298. /* then used for any remaining -- the loop (and the one in a */
  1299. /* moment) is not then on the critical path because the number */
  1300. /* of additions is reduced by (at least) two in this case) */
  1301. UBFROMUI(buf+4, 0); /* [clears decQuad 00 too] */
  1302. UBFROMUI(buf+8, 0);
  1303. if (ub>buf+12) {
  1304. ut=buf+12; /* start any remaining */
  1305. for (; ut<ub; ut+=4) UBFROMUI(ut, 0); /* fill them */
  1306. }
  1307. GETCOEFF(dfr, ub); /* decode from decFloat */
  1308. /* now move tail of rhs across to main acc; again use direct */
  1309. /* copies for 8 digits-worth */
  1310. UBFROMUI(acc+COFF+DECPMAX, UBTOUI(buf+COFF+DECPMAX));
  1311. UBFROMUI(acc+COFF+DECPMAX+4, UBTOUI(buf+COFF+DECPMAX+4));
  1312. if (buf+COFF+DECPMAX+8<ub+DECPMAX) {
  1313. us=buf+COFF+DECPMAX+8; /* source */
  1314. ut=acc+COFF+DECPMAX+8; /* target */
  1315. for (; us<ub+DECPMAX; us+=4, ut+=4) UBFROMUI(ut, UBTOUI(us));
  1316. }
  1317. } /* unaligned */
  1318. ulsd=acc+(ub-buf+DECPMAX-1); /* update LSD pointer */
  1319. /* Now do the add of the non-tail; this is all nicely aligned, */
  1320. /* and is over a multiple of four digits (because for Quad two */
  1321. /* zero digits were added on the left); words in both acc and */
  1322. /* buf (buf especially) will often be zero */
  1323. /* [byte-by-byte add, here, is about 15% slower total effect than */
  1324. /* the by-fours] */
  1325. /* Now effect the add; this is harder on a little-endian */
  1326. /* machine as the inter-digit carry cannot use the usual BCD */
  1327. /* addition trick because the bytes are loaded in the wrong order */
  1328. /* [this loop could be unrolled, but probably scarcely worth it] */
  1329. ut=acc+COFF+DECPMAX-4; /* target LSW (acc) */
  1330. us=buf+COFF+DECPMAX-4; /* source LSW (buf, to add to acc) */
  1331. #if !DECLITEND
  1332. for (; ut>=acc+4; ut-=4, us-=4) { /* big-endian add loop */
  1333. /* bcd8 add */
  1334. carry+=UBTOUI(us); /* rhs + carry */
  1335. if (carry==0) continue; /* no-op */
  1336. carry+=UBTOUI(ut); /* lhs */
  1337. /* Big-endian BCD adjust (uses internal carry) */
  1338. carry+=0x76f6f6f6; /* note top nibble not all bits */
  1339. /* apply BCD adjust and save */
  1340. UBFROMUI(ut, (carry & 0x0f0f0f0f) - ((carry & 0x60606060)>>4));
  1341. carry>>=31; /* true carry was at far left */
  1342. } /* add loop */
  1343. #else
  1344. for (; ut>=acc+4; ut-=4, us-=4) { /* little-endian add loop */
  1345. /* bcd8 add */
  1346. carry+=UBTOUI(us); /* rhs + carry */
  1347. if (carry==0) continue; /* no-op [common if unaligned] */
  1348. carry+=UBTOUI(ut); /* lhs */
  1349. /* Little-endian BCD adjust; inter-digit carry must be manual */
  1350. /* because the lsb from the array will be in the most-significant */
  1351. /* byte of carry */
  1352. carry+=0x76767676; /* note no inter-byte carries */
  1353. carry+=(carry & 0x80000000)>>15;
  1354. carry+=(carry & 0x00800000)>>15;
  1355. carry+=(carry & 0x00008000)>>15;
  1356. carry-=(carry & 0x60606060)>>4; /* BCD adjust back */
  1357. UBFROMUI(ut, carry & 0x0f0f0f0f); /* clear debris and save */
  1358. /* here, final carry-out bit is at 0x00000080; move it ready */
  1359. /* for next word-add (i.e., to 0x01000000) */
  1360. carry=(carry & 0x00000080)<<17;
  1361. } /* add loop */
  1362. #endif
  1363. #if DECTRACE
  1364. {bcdnum tum;
  1365. printf("Add done, carry=%08lx, diffsign=%ld\n", (LI)carry, (LI)diffsign);
  1366. tum.msd=umsd; /* acc+4; */
  1367. tum.lsd=ulsd;
  1368. tum.exponent=0;
  1369. tum.sign=0;
  1370. decShowNum(&tum, "dfadd");}
  1371. #endif
  1372. } /* overlap possible */
  1373. /* ordering here is a little strange in order to have slowest path */
  1374. /* first in GCC asm listing */
  1375. if (diffsign) { /* subtraction */
  1376. if (!carry) { /* no carry out means RHS<LHS */
  1377. /* borrowed -- take ten's complement */
  1378. /* sign is lhs sign */
  1379. num.sign=DFWORD(dfl, 0) & DECFLOAT_Sign;
  1380. /* invert the coefficient first by fours, then add one; space */
  1381. /* at the end of the buffer ensures the by-fours is always */
  1382. /* safe, but lsd+1 must be cleared to prevent a borrow */
  1383. /* if big-endian */
  1384. #if !DECLITEND
  1385. *(ulsd+1)=0;
  1386. #endif
  1387. /* there are always at least four coefficient words */
  1388. UBFROMUI(umsd, 0x09090909-UBTOUI(umsd));
  1389. UBFROMUI(umsd+4, 0x09090909-UBTOUI(umsd+4));
  1390. UBFROMUI(umsd+8, 0x09090909-UBTOUI(umsd+8));
  1391. UBFROMUI(umsd+12, 0x09090909-UBTOUI(umsd+12));
  1392. #if DOUBLE
  1393. #define BNEXT 16
  1394. #elif QUAD
  1395. UBFROMUI(umsd+16, 0x09090909-UBTOUI(umsd+16));
  1396. UBFROMUI(umsd+20, 0x09090909-UBTOUI(umsd+20));
  1397. UBFROMUI(umsd+24, 0x09090909-UBTOUI(umsd+24));
  1398. UBFROMUI(umsd+28, 0x09090909-UBTOUI(umsd+28));
  1399. UBFROMUI(umsd+32, 0x09090909-UBTOUI(umsd+32));
  1400. #define BNEXT 36
  1401. #endif
  1402. if (ulsd>=umsd+BNEXT) { /* unaligned */
  1403. /* eight will handle most unaligments for Double; 16 for Quad */
  1404. UBFROMUI(umsd+BNEXT, 0x09090909-UBTOUI(umsd+BNEXT));
  1405. UBFROMUI(umsd+BNEXT+4, 0x09090909-UBTOUI(umsd+BNEXT+4));
  1406. #if DOUBLE
  1407. #define BNEXTY (BNEXT+8)
  1408. #elif QUAD
  1409. UBFROMUI(umsd+BNEXT+8, 0x09090909-UBTOUI(umsd+BNEXT+8));
  1410. UBFROMUI(umsd+BNEXT+12, 0x09090909-UBTOUI(umsd+BNEXT+12));
  1411. #define BNEXTY (BNEXT+16)
  1412. #endif
  1413. if (ulsd>=umsd+BNEXTY) { /* very unaligned */
  1414. ut=umsd+BNEXTY; /* -> continue */
  1415. for (;;ut+=4) {
  1416. UBFROMUI(ut, 0x09090909-UBTOUI(ut)); /* invert four digits */
  1417. if (ut>=ulsd-3) break; /* all done */
  1418. }
  1419. }
  1420. }
  1421. /* complete the ten's complement by adding 1 */
  1422. for (ub=ulsd; *ub==9; ub--) *ub=0;
  1423. *ub+=1;
  1424. } /* borrowed */
  1425. else { /* carry out means RHS>=LHS */
  1426. num.sign=DFWORD(dfr, 0) & DECFLOAT_Sign;
  1427. /* all done except for the special IEEE 754 exact-zero-result */
  1428. /* rule (see above); while testing for zero, strip leading */
  1429. /* zeros (which will save decFinalize doing it) (this is in */
  1430. /* diffsign path, so carry impossible and true umsd is */
  1431. /* acc+COFF) */
  1432. /* Check the initial coefficient area using the fast macro; */
  1433. /* this will often be all that needs to be done (as on the */
  1434. /* worst-case path when the subtraction was aligned and */
  1435. /* full-length) */
  1436. if (ISCOEFFZERO(acc+COFF)) {
  1437. umsd=acc+COFF+DECPMAX-1; /* so far, so zero */
  1438. if (ulsd>umsd) { /* more to check */
  1439. umsd++; /* to align after checked area */
  1440. for (; UBTOUI(umsd)==0 && umsd+3<ulsd;) umsd+=4;
  1441. for (; *umsd==0 && umsd<ulsd;) umsd++;
  1442. }
  1443. if (*umsd==0) { /* must be true zero (and diffsign) */
  1444. num.sign=0; /* assume + */
  1445. if (set->round==DEC_ROUND_FLOOR) num.sign=DECFLOAT_Sign;
  1446. }
  1447. }
  1448. /* [else was not zero, might still have leading zeros] */
  1449. } /* subtraction gave positive result */
  1450. } /* diffsign */
  1451. else { /* same-sign addition */
  1452. num.sign=DFWORD(dfl, 0)&DECFLOAT_Sign;
  1453. #if DOUBLE
  1454. if (carry) { /* only possible with decDouble */
  1455. *(acc+3)=1; /* [Quad has leading 00] */
  1456. umsd=acc+3;
  1457. }
  1458. #endif
  1459. } /* same sign */
  1460. num.msd=umsd; /* set MSD .. */
  1461. num.lsd=ulsd; /* .. and LSD */
  1462. num.exponent=bexpr-DECBIAS; /* set exponent to smaller, unbiassed */
  1463. #if DECTRACE
  1464. decFloatShow(dfl, "dfl");
  1465. decFloatShow(dfr, "dfr");
  1466. decShowNum(&num, "postadd");
  1467. #endif
  1468. return decFinalize(result, &num, set); /* round, check, and lay out */
  1469. } /* decFloatAdd */
  1470. /* ------------------------------------------------------------------ */
  1471. /* decFloatAnd -- logical digitwise AND of two decFloats */
  1472. /* */
  1473. /* result gets the result of ANDing dfl and dfr */
  1474. /* dfl is the first decFloat (lhs) */
  1475. /* dfr is the second decFloat (rhs) */
  1476. /* set is the context */
  1477. /* returns result, which will be canonical with sign=0 */
  1478. /* */
  1479. /* The operands must be positive, finite with exponent q=0, and */
  1480. /* comprise just zeros and ones; if not, Invalid operation results. */
  1481. /* ------------------------------------------------------------------ */
  1482. decFloat * decFloatAnd(decFloat *result,
  1483. const decFloat *dfl, const decFloat *dfr,
  1484. decContext *set) {
  1485. if (!DFISUINT01(dfl) || !DFISUINT01(dfr)
  1486. || !DFISCC01(dfl) || !DFISCC01(dfr)) return decInvalid(result, set);
  1487. /* the operands are positive finite integers (q=0) with just 0s and 1s */
  1488. #if DOUBLE
  1489. DFWORD(result, 0)=ZEROWORD
  1490. |((DFWORD(dfl, 0) & DFWORD(dfr, 0))&0x04009124);
  1491. DFWORD(result, 1)=(DFWORD(dfl, 1) & DFWORD(dfr, 1))&0x49124491;
  1492. #elif QUAD
  1493. DFWORD(result, 0)=ZEROWORD
  1494. |((DFWORD(dfl, 0) & DFWORD(dfr, 0))&0x04000912);
  1495. DFWORD(result, 1)=(DFWORD(dfl, 1) & DFWORD(dfr, 1))&0x44912449;
  1496. DFWORD(result, 2)=(DFWORD(dfl, 2) & DFWORD(dfr, 2))&0x12449124;
  1497. DFWORD(result, 3)=(DFWORD(dfl, 3) & DFWORD(dfr, 3))&0x49124491;
  1498. #endif
  1499. return result;
  1500. } /* decFloatAnd */
  1501. /* ------------------------------------------------------------------ */
  1502. /* decFloatCanonical -- copy a decFloat, making canonical */
  1503. /* */
  1504. /* result gets the canonicalized df */
  1505. /* df is the decFloat to copy and make canonical */
  1506. /* returns result */
  1507. /* */
  1508. /* This works on specials, too; no error or exception is possible. */
  1509. /* ------------------------------------------------------------------ */
  1510. decFloat * decFloatCanonical(decFloat *result, const decFloat *df) {
  1511. return decCanonical(result, df);
  1512. } /* decFloatCanonical */
  1513. /* ------------------------------------------------------------------ */
  1514. /* decFloatClass -- return the class of a decFloat */
  1515. /* */
  1516. /* df is the decFloat to test */
  1517. /* returns the decClass that df falls into */
  1518. /* ------------------------------------------------------------------ */
  1519. enum decClass decFloatClass(const decFloat *df) {
  1520. Int exp; /* exponent */
  1521. if (DFISSPECIAL(df)) {
  1522. if (DFISQNAN(df)) return DEC_CLASS_QNAN;
  1523. if (DFISSNAN(df)) return DEC_CLASS_SNAN;
  1524. /* must be an infinity */
  1525. if (DFISSIGNED(df)) return DEC_CLASS_NEG_INF;
  1526. return DEC_CLASS_POS_INF;
  1527. }
  1528. if (DFISZERO(df)) { /* quite common */
  1529. if (DFISSIGNED(df)) return DEC_CLASS_NEG_ZERO;
  1530. return DEC_CLASS_POS_ZERO;
  1531. }
  1532. /* is finite and non-zero; similar code to decFloatIsNormal, here */
  1533. /* [this could be speeded up slightly by in-lining decFloatDigits] */
  1534. exp=GETEXPUN(df) /* get unbiased exponent .. */
  1535. +decFloatDigits(df)-1; /* .. and make adjusted exponent */
  1536. if (exp>=DECEMIN) { /* is normal */
  1537. if (DFISSIGNED(df)) return DEC_CLASS_NEG_NORMAL;
  1538. return DEC_CLASS_POS_NORMAL;
  1539. }
  1540. /* is subnormal */
  1541. if (DFISSIGNED(df)) return DEC_CLASS_NEG_SUBNORMAL;
  1542. return DEC_CLASS_POS_SUBNORMAL;
  1543. } /* decFloatClass */
  1544. /* ------------------------------------------------------------------ */
  1545. /* decFloatClassString -- return the class of a decFloat as a string */
  1546. /* */
  1547. /* df is the decFloat to test */
  1548. /* returns a constant string describing the class df falls into */
  1549. /* ------------------------------------------------------------------ */
  1550. const char *decFloatClassString(const decFloat *df) {
  1551. enum decClass eclass=decFloatClass(df);
  1552. if (eclass==DEC_CLASS_POS_NORMAL) return DEC_ClassString_PN;
  1553. if (eclass==DEC_CLASS_NEG_NORMAL) return DEC_ClassString_NN;
  1554. if (eclass==DEC_CLASS_POS_ZERO) return DEC_ClassString_PZ;
  1555. if (eclass==DEC_CLASS_NEG_ZERO) return DEC_ClassString_NZ;
  1556. if (eclass==DEC_CLASS_POS_SUBNORMAL) return DEC_ClassString_PS;
  1557. if (eclass==DEC_CLASS_NEG_SUBNORMAL) return DEC_ClassString_NS;
  1558. if (eclass==DEC_CLASS_POS_INF) return DEC_ClassString_PI;
  1559. if (eclass==DEC_CLASS_NEG_INF) return DEC_ClassString_NI;
  1560. if (eclass==DEC_CLASS_QNAN) return DEC_ClassString_QN;
  1561. if (eclass==DEC_CLASS_SNAN) return DEC_ClassString_SN;
  1562. return DEC_ClassString_UN; /* Unknown */
  1563. } /* decFloatClassString */
  1564. /* ------------------------------------------------------------------ */
  1565. /* decFloatCompare -- compare two decFloats; quiet NaNs allowed */
  1566. /* */
  1567. /* result gets the result of comparing dfl and dfr */
  1568. /* dfl is the first decFloat (lhs) */
  1569. /* dfr is the second decFloat (rhs) */
  1570. /* set is the context */
  1571. /* returns result, which may be -1, 0, 1, or NaN (Unordered) */
  1572. /* ------------------------------------------------------------------ */
  1573. decFloat * decFloatCompare(decFloat *result,
  1574. const decFloat *dfl, const decFloat *dfr,
  1575. decContext *set) {
  1576. Int comp; /* work */
  1577. /* NaNs are handled as usual */
  1578. if (DFISNAN(dfl) || DFISNAN(dfr)) return decNaNs(result, dfl, dfr, set);
  1579. /* numeric comparison needed */
  1580. comp=decNumCompare(dfl, dfr, 0);
  1581. decFloatZero(result);
  1582. if (comp==0) return result;
  1583. DFBYTE(result, DECBYTES-1)=0x01; /* LSD=1 */
  1584. if (comp<0) DFBYTE(result, 0)|=0x80; /* set sign bit */
  1585. return result;
  1586. } /* decFloatCompare */
  1587. /* ------------------------------------------------------------------ */
  1588. /* decFloatCompareSignal -- compare two decFloats; all NaNs signal */
  1589. /* */
  1590. /* result gets the result of comparing dfl and dfr */
  1591. /* dfl is the first decFloat (lhs) */
  1592. /* dfr is the second decFloat (rhs) */
  1593. /* set is the context */
  1594. /* returns result, which may be -1, 0, 1, or NaN (Unordered) */
  1595. /* ------------------------------------------------------------------ */
  1596. decFloat * decFloatCompareSignal(decFloat *result,
  1597. const decFloat *dfl, const decFloat *dfr,
  1598. decContext *set) {
  1599. Int comp; /* work */
  1600. /* NaNs are handled as usual, except that all NaNs signal */
  1601. if (DFISNAN(dfl) || DFISNAN(dfr)) {
  1602. set->status|=DEC_Invalid_operation;
  1603. return decNaNs(result, dfl, dfr, set);
  1604. }
  1605. /* numeric comparison needed */
  1606. comp=decNumCompare(dfl, dfr, 0);
  1607. decFloatZero(result);
  1608. if (comp==0) return result;
  1609. DFBYTE(result, DECBYTES-1)=0x01; /* LSD=1 */
  1610. if (comp<0) DFBYTE(result, 0)|=0x80; /* set sign bit */
  1611. return result;
  1612. } /* decFloatCompareSignal */
  1613. /* ------------------------------------------------------------------ */
  1614. /* decFloatCompareTotal -- compare two decFloats with total ordering */
  1615. /* */
  1616. /* result gets the result of comparing dfl and dfr */
  1617. /* dfl is the first decFloat (lhs) */
  1618. /* dfr is the second decFloat (rhs) */
  1619. /* returns result, which may be -1, 0, or 1 */
  1620. /* ------------------------------------------------------------------ */
  1621. decFloat * decFloatCompareTotal(decFloat *result,
  1622. const decFloat *dfl, const decFloat *dfr) {
  1623. Int comp; /* work */
  1624. uInt uiwork; /* for macros */
  1625. #if QUAD
  1626. uShort uswork; /* .. */
  1627. #endif
  1628. if (DFISNAN(dfl) || DFISNAN(dfr)) {
  1629. Int nanl, nanr; /* work */
  1630. /* morph NaNs to +/- 1 or 2, leave numbers as 0 */
  1631. nanl=DFISSNAN(dfl)+DFISQNAN(dfl)*2; /* quiet > signalling */
  1632. if (DFISSIGNED(dfl)) nanl=-nanl;
  1633. nanr=DFISSNAN(dfr)+DFISQNAN(dfr)*2;
  1634. if (DFISSIGNED(dfr)) nanr=-nanr;
  1635. if (nanl>nanr) comp=+1;
  1636. else if (nanl<nanr) comp=-1;
  1637. else { /* NaNs are the same type and sign .. must compare payload */
  1638. /* buffers need +2 for QUAD */
  1639. uByte bufl[DECPMAX+4]; /* for LHS coefficient + foot */
  1640. uByte bufr[DECPMAX+4]; /* for RHS coefficient + foot */
  1641. uByte *ub, *uc; /* work */
  1642. Int sigl; /* signum of LHS */
  1643. sigl=(DFISSIGNED(dfl) ? -1 : +1);
  1644. /* decode the coefficients */
  1645. /* (shift both right two if Quad to make a multiple of four) */
  1646. #if QUAD
  1647. UBFROMUS(bufl, 0);
  1648. UBFROMUS(bufr, 0);
  1649. #endif
  1650. GETCOEFF(dfl, bufl+QUAD*2); /* decode from decFloat */
  1651. GETCOEFF(dfr, bufr+QUAD*2); /* .. */
  1652. /* all multiples of four, here */
  1653. comp=0; /* assume equal */
  1654. for (ub=bufl, uc=bufr; ub<bufl+DECPMAX+QUAD*2; ub+=4, uc+=4) {
  1655. uInt ui=UBTOUI(ub);
  1656. if (ui==UBTOUI(uc)) continue; /* so far so same */
  1657. /* about to find a winner; go by bytes in case little-endian */
  1658. for (;; ub++, uc++) {
  1659. if (*ub==*uc) continue;
  1660. if (*ub>*uc) comp=sigl; /* difference found */
  1661. else comp=-sigl; /* .. */
  1662. break;
  1663. }
  1664. }
  1665. } /* same NaN type and sign */
  1666. }
  1667. else {
  1668. /* numeric comparison needed */
  1669. comp=decNumCompare(dfl, dfr, 1); /* total ordering */
  1670. }
  1671. decFloatZero(result);
  1672. if (comp==0) return result;
  1673. DFBYTE(result, DECBYTES-1)=0x01; /* LSD=1 */
  1674. if (comp<0) DFBYTE(result, 0)|=0x80; /* set sign bit */
  1675. return result;
  1676. } /* decFloatCompareTotal */
  1677. /* ------------------------------------------------------------------ */
  1678. /* decFloatCompareTotalMag -- compare magnitudes with total ordering */
  1679. /* */
  1680. /* result gets the result of comparing abs(dfl) and abs(dfr) */
  1681. /* dfl is the first decFloat (lhs) */
  1682. /* dfr is the second decFloat (rhs) */
  1683. /* returns result, which may be -1, 0, or 1 */
  1684. /* ------------------------------------------------------------------ */
  1685. decFloat * decFloatCompareTotalMag(decFloat *result,
  1686. const decFloat *dfl, const decFloat *dfr) {
  1687. decFloat a, b; /* for copy if needed */
  1688. /* copy and redirect signed operand(s) */
  1689. if (DFISSIGNED(dfl)) {
  1690. decFloatCopyAbs(&a, dfl);
  1691. dfl=&a;
  1692. }
  1693. if (DFISSIGNED(dfr)) {
  1694. decFloatCopyAbs(&b, dfr);
  1695. dfr=&b;
  1696. }
  1697. return decFloatCompareTotal(result, dfl, dfr);
  1698. } /* decFloatCompareTotalMag */
  1699. /* ------------------------------------------------------------------ */
  1700. /* decFloatCopy -- copy a decFloat as-is */
  1701. /* */
  1702. /* result gets the copy of dfl */
  1703. /* dfl is the decFloat to copy */
  1704. /* returns result */
  1705. /* */
  1706. /* This is a bitwise operation; no errors or exceptions are possible. */
  1707. /* ------------------------------------------------------------------ */
  1708. decFloat * decFloatCopy(decFloat *result, const decFloat *dfl) {
  1709. if (dfl!=result) *result=*dfl; /* copy needed */
  1710. return result;
  1711. } /* decFloatCopy */
  1712. /* ------------------------------------------------------------------ */
  1713. /* decFloatCopyAbs -- copy a decFloat as-is and set sign bit to 0 */
  1714. /* */
  1715. /* result gets the copy of dfl with sign bit 0 */
  1716. /* dfl is the decFloat to copy */
  1717. /* returns result */
  1718. /* */
  1719. /* This is a bitwise operation; no errors or exceptions are possible. */
  1720. /* ------------------------------------------------------------------ */
  1721. decFloat * decFloatCopyAbs(decFloat *result, const decFloat *dfl) {
  1722. if (dfl!=result) *result=*dfl; /* copy needed */
  1723. DFBYTE(result, 0)&=~0x80; /* zero sign bit */
  1724. return result;
  1725. } /* decFloatCopyAbs */
  1726. /* ------------------------------------------------------------------ */
  1727. /* decFloatCopyNegate -- copy a decFloat as-is with inverted sign bit */
  1728. /* */
  1729. /* result gets the copy of dfl with sign bit inverted */
  1730. /* dfl is the decFloat to copy */
  1731. /* returns result */
  1732. /* */
  1733. /* This is a bitwise operation; no errors or exceptions are possible. */
  1734. /* ------------------------------------------------------------------ */
  1735. decFloat * decFloatCopyNegate(decFloat *result, const decFloat *dfl) {
  1736. if (dfl!=result) *result=*dfl; /* copy needed */
  1737. DFBYTE(result, 0)^=0x80; /* invert sign bit */
  1738. return result;
  1739. } /* decFloatCopyNegate */
  1740. /* ------------------------------------------------------------------ */
  1741. /* decFloatCopySign -- copy a decFloat with the sign of another */
  1742. /* */
  1743. /* result gets the result of copying dfl with the sign of dfr */
  1744. /* dfl is the first decFloat (lhs) */
  1745. /* dfr is the second decFloat (rhs) */
  1746. /* returns result */
  1747. /* */
  1748. /* This is a bitwise operation; no errors or exceptions are possible. */
  1749. /* ------------------------------------------------------------------ */
  1750. decFloat * decFloatCopySign(decFloat *result,
  1751. const decFloat *dfl, const decFloat *dfr) {
  1752. uByte sign=(uByte)(DFBYTE(dfr, 0)&0x80); /* save sign bit */
  1753. if (dfl!=result) *result=*dfl; /* copy needed */
  1754. DFBYTE(result, 0)&=~0x80; /* clear sign .. */
  1755. DFBYTE(result, 0)=(uByte)(DFBYTE(result, 0)|sign); /* .. and set saved */
  1756. return result;
  1757. } /* decFloatCopySign */
  1758. /* ------------------------------------------------------------------ */
  1759. /* decFloatDigits -- return the number of digits in a decFloat */
  1760. /* */
  1761. /* df is the decFloat to investigate */
  1762. /* returns the number of significant digits in the decFloat; a */
  1763. /* zero coefficient returns 1 as does an infinity (a NaN returns */
  1764. /* the number of digits in the payload) */
  1765. /* ------------------------------------------------------------------ */
  1766. /* private macro to extract a declet according to provided formula */
  1767. /* (form), and if it is non-zero then return the calculated digits */
  1768. /* depending on the declet number (n), where n=0 for the most */
  1769. /* significant declet; uses uInt dpd for work */
  1770. #define dpdlenchk(n, form) {dpd=(form)&0x3ff; \
  1771. if (dpd) return (DECPMAX-1-3*(n))-(3-DPD2BCD8[dpd*4+3]);}
  1772. /* next one is used when it is known that the declet must be */
  1773. /* non-zero, or is the final zero declet */
  1774. #define dpdlendun(n, form) {dpd=(form)&0x3ff; \
  1775. if (dpd==0) return 1; \
  1776. return (DECPMAX-1-3*(n))-(3-DPD2BCD8[dpd*4+3]);}
  1777. uInt decFloatDigits(const decFloat *df) {
  1778. uInt dpd; /* work */
  1779. uInt sourhi=DFWORD(df, 0); /* top word from source decFloat */
  1780. #if QUAD
  1781. uInt sourmh, sourml;
  1782. #endif
  1783. uInt sourlo;
  1784. if (DFISINF(df)) return 1;
  1785. /* A NaN effectively has an MSD of 0; otherwise if non-zero MSD */
  1786. /* then the coefficient is full-length */
  1787. if (!DFISNAN(df) && DECCOMBMSD[sourhi>>26]) return DECPMAX;
  1788. #if DOUBLE
  1789. if (sourhi&0x0003ffff) { /* ends in first */
  1790. dpdlenchk(0, sourhi>>8);
  1791. sourlo=DFWORD(df, 1);
  1792. dpdlendun(1, (sourhi<<2) | (sourlo>>30));
  1793. } /* [cannot drop through] */
  1794. sourlo=DFWORD(df, 1); /* sourhi not involved now */
  1795. if (sourlo&0xfff00000) { /* in one of first two */
  1796. dpdlenchk(1, sourlo>>30); /* very rare */
  1797. dpdlendun(2, sourlo>>20);
  1798. } /* [cannot drop through] */
  1799. dpdlenchk(3, sourlo>>10);
  1800. dpdlendun(4, sourlo);
  1801. /* [cannot drop through] */
  1802. #elif QUAD
  1803. if (sourhi&0x00003fff) { /* ends in first */
  1804. dpdlenchk(0, sourhi>>4);
  1805. sourmh=DFWORD(df, 1);
  1806. dpdlendun(1, ((sourhi)<<6) | (sourmh>>26));
  1807. } /* [cannot drop through] */
  1808. sourmh=DFWORD(df, 1);
  1809. if (sourmh) {
  1810. dpdlenchk(1, sourmh>>26);
  1811. dpdlenchk(2, sourmh>>16);
  1812. dpdlenchk(3, sourmh>>6);
  1813. sourml=DFWORD(df, 2);
  1814. dpdlendun(4, ((sourmh)<<4) | (sourml>>28));
  1815. } /* [cannot drop through] */
  1816. sourml=DFWORD(df, 2);
  1817. if (sourml) {
  1818. dpdlenchk(4, sourml>>28);
  1819. dpdlenchk(5, sourml>>18);
  1820. dpdlenchk(6, sourml>>8);
  1821. sourlo=DFWORD(df, 3);
  1822. dpdlendun(7, ((sourml)<<2) | (sourlo>>30));
  1823. } /* [cannot drop through] */
  1824. sourlo=DFWORD(df, 3);
  1825. if (sourlo&0xfff00000) { /* in one of first two */
  1826. dpdlenchk(7, sourlo>>30); /* very rare */
  1827. dpdlendun(8, sourlo>>20);
  1828. } /* [cannot drop through] */
  1829. dpdlenchk(9, sourlo>>10);
  1830. dpdlendun(10, sourlo);
  1831. /* [cannot drop through] */
  1832. #endif
  1833. } /* decFloatDigits */
  1834. /* ------------------------------------------------------------------ */
  1835. /* decFloatDivide -- divide a decFloat by another */
  1836. /* */
  1837. /* result gets the result of dividing dfl by dfr: */
  1838. /* dfl is the first decFloat (lhs) */
  1839. /* dfr is the second decFloat (rhs) */
  1840. /* set is the context */
  1841. /* returns result */
  1842. /* */
  1843. /* ------------------------------------------------------------------ */
  1844. /* This is just a wrapper. */
  1845. decFloat * decFloatDivide(decFloat *result,
  1846. const decFloat *dfl, const decFloat *dfr,
  1847. decContext *set) {
  1848. return decDivide(result, dfl, dfr, set, DIVIDE);
  1849. } /* decFloatDivide */
  1850. /* ------------------------------------------------------------------ */
  1851. /* decFloatDivideInteger -- integer divide a decFloat by another */
  1852. /* */
  1853. /* result gets the result of dividing dfl by dfr: */
  1854. /* dfl is the first decFloat (lhs) */
  1855. /* dfr is the second decFloat (rhs) */
  1856. /* set is the context */
  1857. /* returns result */
  1858. /* */
  1859. /* ------------------------------------------------------------------ */
  1860. decFloat * decFloatDivideInteger(decFloat *result,
  1861. const decFloat *dfl, const decFloat *dfr,
  1862. decContext *set) {
  1863. return decDivide(result, dfl, dfr, set, DIVIDEINT);
  1864. } /* decFloatDivideInteger */
  1865. /* ------------------------------------------------------------------ */
  1866. /* decFloatFMA -- multiply and add three decFloats, fused */
  1867. /* */
  1868. /* result gets the result of (dfl*dfr)+dff with a single rounding */
  1869. /* dfl is the first decFloat (lhs) */
  1870. /* dfr is the second decFloat (rhs) */
  1871. /* dff is the final decFloat (fhs) */
  1872. /* set is the context */
  1873. /* returns result */
  1874. /* */
  1875. /* ------------------------------------------------------------------ */
  1876. decFloat * decFloatFMA(decFloat *result, const decFloat *dfl,
  1877. const decFloat *dfr, const decFloat *dff,
  1878. decContext *set) {
  1879. /* The accumulator has the bytes needed for FiniteMultiply, plus */
  1880. /* one byte to the left in case of carry, plus DECPMAX+2 to the */
  1881. /* right for the final addition (up to full fhs + round & sticky) */
  1882. #define FMALEN (ROUNDUP4(1+ (DECPMAX9*18+1) +DECPMAX+2))
  1883. uByte acc[FMALEN]; /* for multiplied coefficient in BCD */
  1884. /* .. and for final result */
  1885. bcdnum mul; /* for multiplication result */
  1886. bcdnum fin; /* for final operand, expanded */
  1887. uByte coe[ROUNDUP4(DECPMAX)]; /* dff coefficient in BCD */
  1888. bcdnum *hi, *lo; /* bcdnum with higher/lower exponent */
  1889. uInt diffsign; /* non-zero if signs differ */
  1890. uInt hipad; /* pad digit for hi if needed */
  1891. Int padding; /* excess exponent */
  1892. uInt carry; /* +1 for ten's complement and during add */
  1893. uByte *ub, *uh, *ul; /* work */
  1894. uInt uiwork; /* for macros */
  1895. /* handle all the special values [any special operand leads to a */
  1896. /* special result] */
  1897. if (DFISSPECIAL(dfl) || DFISSPECIAL(dfr) || DFISSPECIAL(dff)) {
  1898. decFloat proxy; /* multiplication result proxy */
  1899. /* NaNs are handled as usual, giving priority to sNaNs */
  1900. if (DFISSNAN(dfl) || DFISSNAN(dfr)) return decNaNs(result, dfl, dfr, set);
  1901. if (DFISSNAN(dff)) return decNaNs(result, dff, NULL, set);
  1902. if (DFISNAN(dfl) || DFISNAN(dfr)) return decNaNs(result, dfl, dfr, set);
  1903. if (DFISNAN(dff)) return decNaNs(result, dff, NULL, set);
  1904. /* One or more of the three is infinite */
  1905. /* infinity times zero is bad */
  1906. decFloatZero(&proxy);
  1907. if (DFISINF(dfl)) {
  1908. if (DFISZERO(dfr)) return decInvalid(result, set);
  1909. decInfinity(&proxy, &proxy);
  1910. }
  1911. else if (DFISINF(dfr)) {
  1912. if (DFISZERO(dfl)) return decInvalid(result, set);
  1913. decInfinity(&proxy, &proxy);
  1914. }
  1915. /* compute sign of multiplication and place in proxy */
  1916. DFWORD(&proxy, 0)|=(DFWORD(dfl, 0)^DFWORD(dfr, 0))&DECFLOAT_Sign;
  1917. if (!DFISINF(dff)) return decFloatCopy(result, &proxy);
  1918. /* dff is Infinite */
  1919. if (!DFISINF(&proxy)) return decInfinity(result, dff);
  1920. /* both sides of addition are infinite; different sign is bad */
  1921. if ((DFWORD(dff, 0)&DECFLOAT_Sign)!=(DFWORD(&proxy, 0)&DECFLOAT_Sign))
  1922. return decInvalid(result, set);
  1923. return decFloatCopy(result, &proxy);
  1924. }
  1925. /* Here when all operands are finite */
  1926. /* First multiply dfl*dfr */
  1927. decFiniteMultiply(&mul, acc+1, dfl, dfr);
  1928. /* The multiply is complete, exact and unbounded, and described in */
  1929. /* mul with the coefficient held in acc[1...] */
  1930. /* now add in dff; the algorithm is essentially the same as */
  1931. /* decFloatAdd, but the code is different because the code there */
  1932. /* is highly optimized for adding two numbers of the same size */
  1933. fin.exponent=GETEXPUN(dff); /* get dff exponent and sign */
  1934. fin.sign=DFWORD(dff, 0)&DECFLOAT_Sign;
  1935. diffsign=mul.sign^fin.sign; /* note if signs differ */
  1936. fin.msd=coe;
  1937. fin.lsd=coe+DECPMAX-1;
  1938. GETCOEFF(dff, coe); /* extract the coefficient */
  1939. /* now set hi and lo so that hi points to whichever of mul and fin */
  1940. /* has the higher exponent and lo points to the other [don't care, */
  1941. /* if the same]. One coefficient will be in acc, the other in coe. */
  1942. if (mul.exponent>=fin.exponent) {
  1943. hi=&mul;
  1944. lo=&fin;
  1945. }
  1946. else {
  1947. hi=&fin;
  1948. lo=&mul;
  1949. }
  1950. /* remove leading zeros on both operands; this will save time later */
  1951. /* and make testing for zero trivial (tests are safe because acc */
  1952. /* and coe are rounded up to uInts) */
  1953. for (; UBTOUI(hi->msd)==0 && hi->msd+3<hi->lsd;) hi->msd+=4;
  1954. for (; *hi->msd==0 && hi->msd<hi->lsd;) hi->msd++;
  1955. for (; UBTOUI(lo->msd)==0 && lo->msd+3<lo->lsd;) lo->msd+=4;
  1956. for (; *lo->msd==0 && lo->msd<lo->lsd;) lo->msd++;
  1957. /* if hi is zero then result will be lo (which has the smaller */
  1958. /* exponent), which also may need to be tested for zero for the */
  1959. /* weird IEEE 754 sign rules */
  1960. if (*hi->msd==0) { /* hi is zero */
  1961. /* "When the sum of two operands with opposite signs is */
  1962. /* exactly zero, the sign of that sum shall be '+' in all */
  1963. /* rounding modes except round toward -Infinity, in which */
  1964. /* mode that sign shall be '-'." */
  1965. if (diffsign) {
  1966. if (*lo->msd==0) { /* lo is zero */
  1967. lo->sign=0;
  1968. if (set->round==DEC_ROUND_FLOOR) lo->sign=DECFLOAT_Sign;
  1969. } /* diffsign && lo=0 */
  1970. } /* diffsign */
  1971. return decFinalize(result, lo, set); /* may need clamping */
  1972. } /* numfl is zero */
  1973. /* [here, both are minimal length and hi is non-zero] */
  1974. /* (if lo is zero then padding with zeros may be needed, below) */
  1975. /* if signs differ, take the ten's complement of hi (zeros to the */
  1976. /* right do not matter because the complement of zero is zero); the */
  1977. /* +1 is done later, as part of the addition, inserted at the */
  1978. /* correct digit */
  1979. hipad=0;
  1980. carry=0;
  1981. if (diffsign) {
  1982. hipad=9;
  1983. carry=1;
  1984. /* exactly the correct number of digits must be inverted */
  1985. for (uh=hi->msd; uh<hi->lsd-3; uh+=4) UBFROMUI(uh, 0x09090909-UBTOUI(uh));
  1986. for (; uh<=hi->lsd; uh++) *uh=(uByte)(0x09-*uh);
  1987. }
  1988. /* ready to add; note that hi has no leading zeros so gap */
  1989. /* calculation does not have to be as pessimistic as in decFloatAdd */
  1990. /* (this is much more like the arbitrary-precision algorithm in */
  1991. /* Rexx and decNumber) */
  1992. /* padding is the number of zeros that would need to be added to hi */
  1993. /* for its lsd to be aligned with the lsd of lo */
  1994. padding=hi->exponent-lo->exponent;
  1995. /* printf("FMA pad %ld\n", (LI)padding); */
  1996. /* the result of the addition will be built into the accumulator, */
  1997. /* starting from the far right; this could be either hi or lo, and */
  1998. /* will be aligned */
  1999. ub=acc+FMALEN-1; /* where lsd of result will go */
  2000. ul=lo->lsd; /* lsd of rhs */
  2001. if (padding!=0) { /* unaligned */
  2002. /* if the msd of lo is more than DECPMAX+2 digits to the right of */
  2003. /* the original msd of hi then it can be reduced to a single */
  2004. /* digit at the right place, as it stays clear of hi digits */
  2005. /* [it must be DECPMAX+2 because during a subtraction the msd */
  2006. /* could become 0 after a borrow from 1.000 to 0.9999...] */
  2007. Int hilen=(Int)(hi->lsd-hi->msd+1); /* length of hi */
  2008. Int lolen=(Int)(lo->lsd-lo->msd+1); /* and of lo */
  2009. if (hilen+padding-lolen > DECPMAX+2) { /* can reduce lo to single */
  2010. /* make sure it is virtually at least DECPMAX from hi->msd, at */
  2011. /* least to right of hi->lsd (in case of destructive subtract), */
  2012. /* and separated by at least two digits from either of those */
  2013. /* (the tricky DOUBLE case is when hi is a 1 that will become a */
  2014. /* 0.9999... by subtraction: */
  2015. /* hi: 1 E+16 */
  2016. /* lo: .................1000000000000000 E-16 */
  2017. /* which for the addition pads to: */
  2018. /* hi: 1000000000000000000 E-16 */
  2019. /* lo: .................1000000000000000 E-16 */
  2020. Int newexp=MINI(hi->exponent, hi->exponent+hilen-DECPMAX)-3;
  2021. /* printf("FMA reduce: %ld\n", (LI)reduce); */
  2022. lo->lsd=lo->msd; /* to single digit [maybe 0] */
  2023. lo->exponent=newexp; /* new lowest exponent */
  2024. padding=hi->exponent-lo->exponent; /* recalculate */
  2025. ul=lo->lsd; /* .. and repoint */
  2026. }
  2027. /* padding is still > 0, but will fit in acc (less leading carry slot) */
  2028. #if DECCHECK
  2029. if (padding<=0) printf("FMA low padding: %ld\n", (LI)padding);
  2030. if (hilen+padding+1>FMALEN)
  2031. printf("FMA excess hilen+padding: %ld+%ld \n", (LI)hilen, (LI)padding);
  2032. /* printf("FMA padding: %ld\n", (LI)padding); */
  2033. #endif
  2034. /* padding digits can now be set in the result; one or more of */
  2035. /* these will come from lo; others will be zeros in the gap */
  2036. for (; ul-3>=lo->msd && padding>3; padding-=4, ul-=4, ub-=4) {
  2037. UBFROMUI(ub-3, UBTOUI(ul-3)); /* [cannot overlap] */
  2038. }
  2039. for (; ul>=lo->msd && padding>0; padding--, ul--, ub--) *ub=*ul;
  2040. for (;padding>0; padding--, ub--) *ub=0; /* mind the gap */
  2041. }
  2042. /* addition now complete to the right of the rightmost digit of hi */
  2043. uh=hi->lsd;
  2044. /* dow do the add from hi->lsd to the left */
  2045. /* [bytewise, because either operand can run out at any time] */
  2046. /* carry was set up depending on ten's complement above */
  2047. /* first assume both operands have some digits */
  2048. for (;; ub--) {
  2049. if (uh<hi->msd || ul<lo->msd) break;
  2050. *ub=(uByte)(carry+(*uh--)+(*ul--));
  2051. carry=0;
  2052. if (*ub<10) continue;
  2053. *ub-=10;
  2054. carry=1;
  2055. } /* both loop */
  2056. if (ul<lo->msd) { /* to left of lo */
  2057. for (;; ub--) {
  2058. if (uh<hi->msd) break;
  2059. *ub=(uByte)(carry+(*uh--)); /* [+0] */
  2060. carry=0;
  2061. if (*ub<10) continue;
  2062. *ub-=10;
  2063. carry=1;
  2064. } /* hi loop */
  2065. }
  2066. else { /* to left of hi */
  2067. for (;; ub--) {
  2068. if (ul<lo->msd) break;
  2069. *ub=(uByte)(carry+hipad+(*ul--));
  2070. carry=0;
  2071. if (*ub<10) continue;
  2072. *ub-=10;
  2073. carry=1;
  2074. } /* lo loop */
  2075. }
  2076. /* addition complete -- now handle carry, borrow, etc. */
  2077. /* use lo to set up the num (its exponent is already correct, and */
  2078. /* sign usually is) */
  2079. lo->msd=ub+1;
  2080. lo->lsd=acc+FMALEN-1;
  2081. /* decShowNum(lo, "lo"); */
  2082. if (!diffsign) { /* same-sign addition */
  2083. if (carry) { /* carry out */
  2084. *ub=1; /* place the 1 .. */
  2085. lo->msd--; /* .. and update */
  2086. }
  2087. } /* same sign */
  2088. else { /* signs differed (subtraction) */
  2089. if (!carry) { /* no carry out means hi<lo */
  2090. /* borrowed -- take ten's complement of the right digits */
  2091. lo->sign=hi->sign; /* sign is lhs sign */
  2092. for (ul=lo->msd; ul<lo->lsd-3; ul+=4) UBFROMUI(ul, 0x09090909-UBTOUI(ul));
  2093. for (; ul<=lo->lsd; ul++) *ul=(uByte)(0x09-*ul); /* [leaves ul at lsd+1] */
  2094. /* complete the ten's complement by adding 1 [cannot overrun] */
  2095. for (ul--; *ul==9; ul--) *ul=0;
  2096. *ul+=1;
  2097. } /* borrowed */
  2098. else { /* carry out means hi>=lo */
  2099. /* sign to use is lo->sign */
  2100. /* all done except for the special IEEE 754 exact-zero-result */
  2101. /* rule (see above); while testing for zero, strip leading */
  2102. /* zeros (which will save decFinalize doing it) */
  2103. for (; UBTOUI(lo->msd)==0 && lo->msd+3<lo->lsd;) lo->msd+=4;
  2104. for (; *lo->msd==0 && lo->msd<lo->lsd;) lo->msd++;
  2105. if (*lo->msd==0) { /* must be true zero (and diffsign) */
  2106. lo->sign=0; /* assume + */
  2107. if (set->round==DEC_ROUND_FLOOR) lo->sign=DECFLOAT_Sign;
  2108. }
  2109. /* [else was not zero, might still have leading zeros] */
  2110. } /* subtraction gave positive result */
  2111. } /* diffsign */
  2112. #if DECCHECK
  2113. /* assert no left underrun */
  2114. if (lo->msd<acc) {
  2115. printf("FMA underrun by %ld \n", (LI)(acc-lo->msd));
  2116. }
  2117. #endif
  2118. return decFinalize(result, lo, set); /* round, check, and lay out */
  2119. } /* decFloatFMA */
  2120. /* ------------------------------------------------------------------ */
  2121. /* decFloatFromInt -- initialise a decFloat from an Int */
  2122. /* */
  2123. /* result gets the converted Int */
  2124. /* n is the Int to convert */
  2125. /* returns result */
  2126. /* */
  2127. /* The result is Exact; no errors or exceptions are possible. */
  2128. /* ------------------------------------------------------------------ */
  2129. decFloat * decFloatFromInt32(decFloat *result, Int n) {
  2130. uInt u=(uInt)n; /* copy as bits */
  2131. uInt encode; /* work */
  2132. DFWORD(result, 0)=ZEROWORD; /* always */
  2133. #if QUAD
  2134. DFWORD(result, 1)=0;
  2135. DFWORD(result, 2)=0;
  2136. #endif
  2137. if (n<0) { /* handle -n with care */
  2138. /* [This can be done without the test, but is then slightly slower] */
  2139. u=(~u)+1;
  2140. DFWORD(result, 0)|=DECFLOAT_Sign;
  2141. }
  2142. /* Since the maximum value of u now is 2**31, only the low word of */
  2143. /* result is affected */
  2144. encode=BIN2DPD[u%1000];
  2145. u/=1000;
  2146. encode|=BIN2DPD[u%1000]<<10;
  2147. u/=1000;
  2148. encode|=BIN2DPD[u%1000]<<20;
  2149. u/=1000; /* now 0, 1, or 2 */
  2150. encode|=u<<30;
  2151. DFWORD(result, DECWORDS-1)=encode;
  2152. return result;
  2153. } /* decFloatFromInt32 */
  2154. /* ------------------------------------------------------------------ */
  2155. /* decFloatFromUInt -- initialise a decFloat from a uInt */
  2156. /* */
  2157. /* result gets the converted uInt */
  2158. /* n is the uInt to convert */
  2159. /* returns result */
  2160. /* */
  2161. /* The result is Exact; no errors or exceptions are possible. */
  2162. /* ------------------------------------------------------------------ */
  2163. decFloat * decFloatFromUInt32(decFloat *result, uInt u) {
  2164. uInt encode; /* work */
  2165. DFWORD(result, 0)=ZEROWORD; /* always */
  2166. #if QUAD
  2167. DFWORD(result, 1)=0;
  2168. DFWORD(result, 2)=0;
  2169. #endif
  2170. encode=BIN2DPD[u%1000];
  2171. u/=1000;
  2172. encode|=BIN2DPD[u%1000]<<10;
  2173. u/=1000;
  2174. encode|=BIN2DPD[u%1000]<<20;
  2175. u/=1000; /* now 0 -> 4 */
  2176. encode|=u<<30;
  2177. DFWORD(result, DECWORDS-1)=encode;
  2178. DFWORD(result, DECWORDS-2)|=u>>2; /* rarely non-zero */
  2179. return result;
  2180. } /* decFloatFromUInt32 */
  2181. /* ------------------------------------------------------------------ */
  2182. /* decFloatInvert -- logical digitwise INVERT of a decFloat */
  2183. /* */
  2184. /* result gets the result of INVERTing df */
  2185. /* df is the decFloat to invert */
  2186. /* set is the context */
  2187. /* returns result, which will be canonical with sign=0 */
  2188. /* */
  2189. /* The operand must be positive, finite with exponent q=0, and */
  2190. /* comprise just zeros and ones; if not, Invalid operation results. */
  2191. /* ------------------------------------------------------------------ */
  2192. decFloat * decFloatInvert(decFloat *result, const decFloat *df,
  2193. decContext *set) {
  2194. uInt sourhi=DFWORD(df, 0); /* top word of dfs */
  2195. if (!DFISUINT01(df) || !DFISCC01(df)) return decInvalid(result, set);
  2196. /* the operand is a finite integer (q=0) */
  2197. #if DOUBLE
  2198. DFWORD(result, 0)=ZEROWORD|((~sourhi)&0x04009124);
  2199. DFWORD(result, 1)=(~DFWORD(df, 1)) &0x49124491;
  2200. #elif QUAD
  2201. DFWORD(result, 0)=ZEROWORD|((~sourhi)&0x04000912);
  2202. DFWORD(result, 1)=(~DFWORD(df, 1)) &0x44912449;
  2203. DFWORD(result, 2)=(~DFWORD(df, 2)) &0x12449124;
  2204. DFWORD(result, 3)=(~DFWORD(df, 3)) &0x49124491;
  2205. #endif
  2206. return result;
  2207. } /* decFloatInvert */
  2208. /* ------------------------------------------------------------------ */
  2209. /* decFloatIs -- decFloat tests (IsSigned, etc.) */
  2210. /* */
  2211. /* df is the decFloat to test */
  2212. /* returns 0 or 1 in a uInt */
  2213. /* */
  2214. /* Many of these could be macros, but having them as real functions */
  2215. /* is a little cleaner (and they can be referred to here by the */
  2216. /* generic names) */
  2217. /* ------------------------------------------------------------------ */
  2218. uInt decFloatIsCanonical(const decFloat *df) {
  2219. if (DFISSPECIAL(df)) {
  2220. if (DFISINF(df)) {
  2221. if (DFWORD(df, 0)&ECONMASK) return 0; /* exponent continuation */
  2222. if (!DFISCCZERO(df)) return 0; /* coefficient continuation */
  2223. return 1;
  2224. }
  2225. /* is a NaN */
  2226. if (DFWORD(df, 0)&ECONNANMASK) return 0; /* exponent continuation */
  2227. if (DFISCCZERO(df)) return 1; /* coefficient continuation */
  2228. /* drop through to check payload */
  2229. }
  2230. { /* declare block */
  2231. #if DOUBLE
  2232. uInt sourhi=DFWORD(df, 0);
  2233. uInt sourlo=DFWORD(df, 1);
  2234. if (CANONDPDOFF(sourhi, 8)
  2235. && CANONDPDTWO(sourhi, sourlo, 30)
  2236. && CANONDPDOFF(sourlo, 20)
  2237. && CANONDPDOFF(sourlo, 10)
  2238. && CANONDPDOFF(sourlo, 0)) return 1;
  2239. #elif QUAD
  2240. uInt sourhi=DFWORD(df, 0);
  2241. uInt sourmh=DFWORD(df, 1);
  2242. uInt sourml=DFWORD(df, 2);
  2243. uInt sourlo=DFWORD(df, 3);
  2244. if (CANONDPDOFF(sourhi, 4)
  2245. && CANONDPDTWO(sourhi, sourmh, 26)
  2246. && CANONDPDOFF(sourmh, 16)
  2247. && CANONDPDOFF(sourmh, 6)
  2248. && CANONDPDTWO(sourmh, sourml, 28)
  2249. && CANONDPDOFF(sourml, 18)
  2250. && CANONDPDOFF(sourml, 8)
  2251. && CANONDPDTWO(sourml, sourlo, 30)
  2252. && CANONDPDOFF(sourlo, 20)
  2253. && CANONDPDOFF(sourlo, 10)
  2254. && CANONDPDOFF(sourlo, 0)) return 1;
  2255. #endif
  2256. } /* block */
  2257. return 0; /* a declet is non-canonical */
  2258. }
  2259. uInt decFloatIsFinite(const decFloat *df) {
  2260. return !DFISSPECIAL(df);
  2261. }
  2262. uInt decFloatIsInfinite(const decFloat *df) {
  2263. return DFISINF(df);
  2264. }
  2265. uInt decFloatIsInteger(const decFloat *df) {
  2266. return DFISINT(df);
  2267. }
  2268. uInt decFloatIsNaN(const decFloat *df) {
  2269. return DFISNAN(df);
  2270. }
  2271. uInt decFloatIsNormal(const decFloat *df) {
  2272. Int exp; /* exponent */
  2273. if (DFISSPECIAL(df)) return 0;
  2274. if (DFISZERO(df)) return 0;
  2275. /* is finite and non-zero */
  2276. exp=GETEXPUN(df) /* get unbiased exponent .. */
  2277. +decFloatDigits(df)-1; /* .. and make adjusted exponent */
  2278. return (exp>=DECEMIN); /* < DECEMIN is subnormal */
  2279. }
  2280. uInt decFloatIsSignaling(const decFloat *df) {
  2281. return DFISSNAN(df);
  2282. }
  2283. uInt decFloatIsSignalling(const decFloat *df) {
  2284. return DFISSNAN(df);
  2285. }
  2286. uInt decFloatIsSigned(const decFloat *df) {
  2287. return DFISSIGNED(df);
  2288. }
  2289. uInt decFloatIsSubnormal(const decFloat *df) {
  2290. if (DFISSPECIAL(df)) return 0;
  2291. /* is finite */
  2292. if (decFloatIsNormal(df)) return 0;
  2293. /* it is <Nmin, but could be zero */
  2294. if (DFISZERO(df)) return 0;
  2295. return 1; /* is subnormal */
  2296. }
  2297. uInt decFloatIsZero(const decFloat *df) {
  2298. return DFISZERO(df);
  2299. } /* decFloatIs... */
  2300. /* ------------------------------------------------------------------ */
  2301. /* decFloatLogB -- return adjusted exponent, by 754 rules */
  2302. /* */
  2303. /* result gets the adjusted exponent as an integer, or a NaN etc. */
  2304. /* df is the decFloat to be examined */
  2305. /* set is the context */
  2306. /* returns result */
  2307. /* */
  2308. /* Notable cases: */
  2309. /* A<0 -> Use |A| */
  2310. /* A=0 -> -Infinity (Division by zero) */
  2311. /* A=Infinite -> +Infinity (Exact) */
  2312. /* A=1 exactly -> 0 (Exact) */
  2313. /* NaNs are propagated as usual */
  2314. /* ------------------------------------------------------------------ */
  2315. decFloat * decFloatLogB(decFloat *result, const decFloat *df,
  2316. decContext *set) {
  2317. Int ae; /* adjusted exponent */
  2318. if (DFISNAN(df)) return decNaNs(result, df, NULL, set);
  2319. if (DFISINF(df)) {
  2320. DFWORD(result, 0)=0; /* need +ve */
  2321. return decInfinity(result, result); /* canonical +Infinity */
  2322. }
  2323. if (DFISZERO(df)) {
  2324. set->status|=DEC_Division_by_zero; /* as per 754 */
  2325. DFWORD(result, 0)=DECFLOAT_Sign; /* make negative */
  2326. return decInfinity(result, result); /* canonical -Infinity */
  2327. }
  2328. ae=GETEXPUN(df) /* get unbiased exponent .. */
  2329. +decFloatDigits(df)-1; /* .. and make adjusted exponent */
  2330. /* ae has limited range (3 digits for DOUBLE and 4 for QUAD), so */
  2331. /* it is worth using a special case of decFloatFromInt32 */
  2332. DFWORD(result, 0)=ZEROWORD; /* always */
  2333. if (ae<0) {
  2334. DFWORD(result, 0)|=DECFLOAT_Sign; /* -0 so far */
  2335. ae=-ae;
  2336. }
  2337. #if DOUBLE
  2338. DFWORD(result, 1)=BIN2DPD[ae]; /* a single declet */
  2339. #elif QUAD
  2340. DFWORD(result, 1)=0;
  2341. DFWORD(result, 2)=0;
  2342. DFWORD(result, 3)=(ae/1000)<<10; /* is <10, so need no DPD encode */
  2343. DFWORD(result, 3)|=BIN2DPD[ae%1000];
  2344. #endif
  2345. return result;
  2346. } /* decFloatLogB */
  2347. /* ------------------------------------------------------------------ */
  2348. /* decFloatMax -- return maxnum of two operands */
  2349. /* */
  2350. /* result gets the chosen decFloat */
  2351. /* dfl is the first decFloat (lhs) */
  2352. /* dfr is the second decFloat (rhs) */
  2353. /* set is the context */
  2354. /* returns result */
  2355. /* */
  2356. /* If just one operand is a quiet NaN it is ignored. */
  2357. /* ------------------------------------------------------------------ */
  2358. decFloat * decFloatMax(decFloat *result,
  2359. const decFloat *dfl, const decFloat *dfr,
  2360. decContext *set) {
  2361. Int comp;
  2362. if (DFISNAN(dfl)) {
  2363. /* sNaN or both NaNs leads to normal NaN processing */
  2364. if (DFISNAN(dfr) || DFISSNAN(dfl)) return decNaNs(result, dfl, dfr, set);
  2365. return decCanonical(result, dfr); /* RHS is numeric */
  2366. }
  2367. if (DFISNAN(dfr)) {
  2368. /* sNaN leads to normal NaN processing (both NaN handled above) */
  2369. if (DFISSNAN(dfr)) return decNaNs(result, dfl, dfr, set);
  2370. return decCanonical(result, dfl); /* LHS is numeric */
  2371. }
  2372. /* Both operands are numeric; numeric comparison needed -- use */
  2373. /* total order for a well-defined choice (and +0 > -0) */
  2374. comp=decNumCompare(dfl, dfr, 1);
  2375. if (comp>=0) return decCanonical(result, dfl);
  2376. return decCanonical(result, dfr);
  2377. } /* decFloatMax */
  2378. /* ------------------------------------------------------------------ */
  2379. /* decFloatMaxMag -- return maxnummag of two operands */
  2380. /* */
  2381. /* result gets the chosen decFloat */
  2382. /* dfl is the first decFloat (lhs) */
  2383. /* dfr is the second decFloat (rhs) */
  2384. /* set is the context */
  2385. /* returns result */
  2386. /* */
  2387. /* Returns according to the magnitude comparisons if both numeric and */
  2388. /* unequal, otherwise returns maxnum */
  2389. /* ------------------------------------------------------------------ */
  2390. decFloat * decFloatMaxMag(decFloat *result,
  2391. const decFloat *dfl, const decFloat *dfr,
  2392. decContext *set) {
  2393. Int comp;
  2394. decFloat absl, absr;
  2395. if (DFISNAN(dfl) || DFISNAN(dfr)) return decFloatMax(result, dfl, dfr, set);
  2396. decFloatCopyAbs(&absl, dfl);
  2397. decFloatCopyAbs(&absr, dfr);
  2398. comp=decNumCompare(&absl, &absr, 0);
  2399. if (comp>0) return decCanonical(result, dfl);
  2400. if (comp<0) return decCanonical(result, dfr);
  2401. return decFloatMax(result, dfl, dfr, set);
  2402. } /* decFloatMaxMag */
  2403. /* ------------------------------------------------------------------ */
  2404. /* decFloatMin -- return minnum of two operands */
  2405. /* */
  2406. /* result gets the chosen decFloat */
  2407. /* dfl is the first decFloat (lhs) */
  2408. /* dfr is the second decFloat (rhs) */
  2409. /* set is the context */
  2410. /* returns result */
  2411. /* */
  2412. /* If just one operand is a quiet NaN it is ignored. */
  2413. /* ------------------------------------------------------------------ */
  2414. decFloat * decFloatMin(decFloat *result,
  2415. const decFloat *dfl, const decFloat *dfr,
  2416. decContext *set) {
  2417. Int comp;
  2418. if (DFISNAN(dfl)) {
  2419. /* sNaN or both NaNs leads to normal NaN processing */
  2420. if (DFISNAN(dfr) || DFISSNAN(dfl)) return decNaNs(result, dfl, dfr, set);
  2421. return decCanonical(result, dfr); /* RHS is numeric */
  2422. }
  2423. if (DFISNAN(dfr)) {
  2424. /* sNaN leads to normal NaN processing (both NaN handled above) */
  2425. if (DFISSNAN(dfr)) return decNaNs(result, dfl, dfr, set);
  2426. return decCanonical(result, dfl); /* LHS is numeric */
  2427. }
  2428. /* Both operands are numeric; numeric comparison needed -- use */
  2429. /* total order for a well-defined choice (and +0 > -0) */
  2430. comp=decNumCompare(dfl, dfr, 1);
  2431. if (comp<=0) return decCanonical(result, dfl);
  2432. return decCanonical(result, dfr);
  2433. } /* decFloatMin */
  2434. /* ------------------------------------------------------------------ */
  2435. /* decFloatMinMag -- return minnummag of two operands */
  2436. /* */
  2437. /* result gets the chosen decFloat */
  2438. /* dfl is the first decFloat (lhs) */
  2439. /* dfr is the second decFloat (rhs) */
  2440. /* set is the context */
  2441. /* returns result */
  2442. /* */
  2443. /* Returns according to the magnitude comparisons if both numeric and */
  2444. /* unequal, otherwise returns minnum */
  2445. /* ------------------------------------------------------------------ */
  2446. decFloat * decFloatMinMag(decFloat *result,
  2447. const decFloat *dfl, const decFloat *dfr,
  2448. decContext *set) {
  2449. Int comp;
  2450. decFloat absl, absr;
  2451. if (DFISNAN(dfl) || DFISNAN(dfr)) return decFloatMin(result, dfl, dfr, set);
  2452. decFloatCopyAbs(&absl, dfl);
  2453. decFloatCopyAbs(&absr, dfr);
  2454. comp=decNumCompare(&absl, &absr, 0);
  2455. if (comp<0) return decCanonical(result, dfl);
  2456. if (comp>0) return decCanonical(result, dfr);
  2457. return decFloatMin(result, dfl, dfr, set);
  2458. } /* decFloatMinMag */
  2459. /* ------------------------------------------------------------------ */
  2460. /* decFloatMinus -- negate value, heeding NaNs, etc. */
  2461. /* */
  2462. /* result gets the canonicalized 0-df */
  2463. /* df is the decFloat to minus */
  2464. /* set is the context */
  2465. /* returns result */
  2466. /* */
  2467. /* This has the same effect as 0-df where the exponent of the zero is */
  2468. /* the same as that of df (if df is finite). */
  2469. /* The effect is also the same as decFloatCopyNegate except that NaNs */
  2470. /* are handled normally (the sign of a NaN is not affected, and an */
  2471. /* sNaN will signal), the result is canonical, and zero gets sign 0. */
  2472. /* ------------------------------------------------------------------ */
  2473. decFloat * decFloatMinus(decFloat *result, const decFloat *df,
  2474. decContext *set) {
  2475. if (DFISNAN(df)) return decNaNs(result, df, NULL, set);
  2476. decCanonical(result, df); /* copy and check */
  2477. if (DFISZERO(df)) DFBYTE(result, 0)&=~0x80; /* turn off sign bit */
  2478. else DFBYTE(result, 0)^=0x80; /* flip sign bit */
  2479. return result;
  2480. } /* decFloatMinus */
  2481. /* ------------------------------------------------------------------ */
  2482. /* decFloatMultiply -- multiply two decFloats */
  2483. /* */
  2484. /* result gets the result of multiplying dfl and dfr: */
  2485. /* dfl is the first decFloat (lhs) */
  2486. /* dfr is the second decFloat (rhs) */
  2487. /* set is the context */
  2488. /* returns result */
  2489. /* */
  2490. /* ------------------------------------------------------------------ */
  2491. decFloat * decFloatMultiply(decFloat *result,
  2492. const decFloat *dfl, const decFloat *dfr,
  2493. decContext *set) {
  2494. bcdnum num; /* for final conversion */
  2495. uByte bcdacc[DECPMAX9*18+1]; /* for coefficent in BCD */
  2496. if (DFISSPECIAL(dfl) || DFISSPECIAL(dfr)) { /* either is special? */
  2497. /* NaNs are handled as usual */
  2498. if (DFISNAN(dfl) || DFISNAN(dfr)) return decNaNs(result, dfl, dfr, set);
  2499. /* infinity times zero is bad */
  2500. if (DFISINF(dfl) && DFISZERO(dfr)) return decInvalid(result, set);
  2501. if (DFISINF(dfr) && DFISZERO(dfl)) return decInvalid(result, set);
  2502. /* both infinite; return canonical infinity with computed sign */
  2503. DFWORD(result, 0)=DFWORD(dfl, 0)^DFWORD(dfr, 0); /* compute sign */
  2504. return decInfinity(result, result);
  2505. }
  2506. /* Here when both operands are finite */
  2507. decFiniteMultiply(&num, bcdacc, dfl, dfr);
  2508. return decFinalize(result, &num, set); /* round, check, and lay out */
  2509. } /* decFloatMultiply */
  2510. /* ------------------------------------------------------------------ */
  2511. /* decFloatNextMinus -- next towards -Infinity */
  2512. /* */
  2513. /* result gets the next lesser decFloat */
  2514. /* dfl is the decFloat to start with */
  2515. /* set is the context */
  2516. /* returns result */
  2517. /* */
  2518. /* This is 754 nextdown; Invalid is the only status possible (from */
  2519. /* an sNaN). */
  2520. /* ------------------------------------------------------------------ */
  2521. decFloat * decFloatNextMinus(decFloat *result, const decFloat *dfl,
  2522. decContext *set) {
  2523. decFloat delta; /* tiny increment */
  2524. uInt savestat; /* saves status */
  2525. enum rounding saveround; /* .. and mode */
  2526. /* +Infinity is the special case */
  2527. if (DFISINF(dfl) && !DFISSIGNED(dfl)) {
  2528. DFSETNMAX(result);
  2529. return result; /* [no status to set] */
  2530. }
  2531. /* other cases are effected by sutracting a tiny delta -- this */
  2532. /* should be done in a wider format as the delta is unrepresentable */
  2533. /* here (but can be done with normal add if the sign of zero is */
  2534. /* treated carefully, because no Inexactitude is interesting); */
  2535. /* rounding to -Infinity then pushes the result to next below */
  2536. decFloatZero(&delta); /* set up tiny delta */
  2537. DFWORD(&delta, DECWORDS-1)=1; /* coefficient=1 */
  2538. DFWORD(&delta, 0)=DECFLOAT_Sign; /* Sign=1 + biased exponent=0 */
  2539. /* set up for the directional round */
  2540. saveround=set->round; /* save mode */
  2541. set->round=DEC_ROUND_FLOOR; /* .. round towards -Infinity */
  2542. savestat=set->status; /* save status */
  2543. decFloatAdd(result, dfl, &delta, set);
  2544. /* Add rules mess up the sign when going from +Ntiny to 0 */
  2545. if (DFISZERO(result)) DFWORD(result, 0)^=DECFLOAT_Sign; /* correct */
  2546. set->status&=DEC_Invalid_operation; /* preserve only sNaN status */
  2547. set->status|=savestat; /* restore pending flags */
  2548. set->round=saveround; /* .. and mode */
  2549. return result;
  2550. } /* decFloatNextMinus */
  2551. /* ------------------------------------------------------------------ */
  2552. /* decFloatNextPlus -- next towards +Infinity */
  2553. /* */
  2554. /* result gets the next larger decFloat */
  2555. /* dfl is the decFloat to start with */
  2556. /* set is the context */
  2557. /* returns result */
  2558. /* */
  2559. /* This is 754 nextup; Invalid is the only status possible (from */
  2560. /* an sNaN). */
  2561. /* ------------------------------------------------------------------ */
  2562. decFloat * decFloatNextPlus(decFloat *result, const decFloat *dfl,
  2563. decContext *set) {
  2564. uInt savestat; /* saves status */
  2565. enum rounding saveround; /* .. and mode */
  2566. decFloat delta; /* tiny increment */
  2567. /* -Infinity is the special case */
  2568. if (DFISINF(dfl) && DFISSIGNED(dfl)) {
  2569. DFSETNMAX(result);
  2570. DFWORD(result, 0)|=DECFLOAT_Sign; /* make negative */
  2571. return result; /* [no status to set] */
  2572. }
  2573. /* other cases are effected by sutracting a tiny delta -- this */
  2574. /* should be done in a wider format as the delta is unrepresentable */
  2575. /* here (but can be done with normal add if the sign of zero is */
  2576. /* treated carefully, because no Inexactitude is interesting); */
  2577. /* rounding to +Infinity then pushes the result to next above */
  2578. decFloatZero(&delta); /* set up tiny delta */
  2579. DFWORD(&delta, DECWORDS-1)=1; /* coefficient=1 */
  2580. DFWORD(&delta, 0)=0; /* Sign=0 + biased exponent=0 */
  2581. /* set up for the directional round */
  2582. saveround=set->round; /* save mode */
  2583. set->round=DEC_ROUND_CEILING; /* .. round towards +Infinity */
  2584. savestat=set->status; /* save status */
  2585. decFloatAdd(result, dfl, &delta, set);
  2586. /* Add rules mess up the sign when going from -Ntiny to -0 */
  2587. if (DFISZERO(result)) DFWORD(result, 0)^=DECFLOAT_Sign; /* correct */
  2588. set->status&=DEC_Invalid_operation; /* preserve only sNaN status */
  2589. set->status|=savestat; /* restore pending flags */
  2590. set->round=saveround; /* .. and mode */
  2591. return result;
  2592. } /* decFloatNextPlus */
  2593. /* ------------------------------------------------------------------ */
  2594. /* decFloatNextToward -- next towards a decFloat */
  2595. /* */
  2596. /* result gets the next decFloat */
  2597. /* dfl is the decFloat to start with */
  2598. /* dfr is the decFloat to move toward */
  2599. /* set is the context */
  2600. /* returns result */
  2601. /* */
  2602. /* This is 754-1985 nextafter, as modified during revision (dropped */
  2603. /* from 754-2008); status may be set unless the result is a normal */
  2604. /* number. */
  2605. /* ------------------------------------------------------------------ */
  2606. decFloat * decFloatNextToward(decFloat *result,
  2607. const decFloat *dfl, const decFloat *dfr,
  2608. decContext *set) {
  2609. decFloat delta; /* tiny increment or decrement */
  2610. decFloat pointone; /* 1e-1 */
  2611. uInt savestat; /* saves status */
  2612. enum rounding saveround; /* .. and mode */
  2613. uInt deltatop; /* top word for delta */
  2614. Int comp; /* work */
  2615. if (DFISNAN(dfl) || DFISNAN(dfr)) return decNaNs(result, dfl, dfr, set);
  2616. /* Both are numeric, so Invalid no longer a possibility */
  2617. comp=decNumCompare(dfl, dfr, 0);
  2618. if (comp==0) return decFloatCopySign(result, dfl, dfr); /* equal */
  2619. /* unequal; do NextPlus or NextMinus but with different status rules */
  2620. if (comp<0) { /* lhs<rhs, do NextPlus, see above for commentary */
  2621. if (DFISINF(dfl) && DFISSIGNED(dfl)) { /* -Infinity special case */
  2622. DFSETNMAX(result);
  2623. DFWORD(result, 0)|=DECFLOAT_Sign;
  2624. return result;
  2625. }
  2626. saveround=set->round; /* save mode */
  2627. set->round=DEC_ROUND_CEILING; /* .. round towards +Infinity */
  2628. deltatop=0; /* positive delta */
  2629. }
  2630. else { /* lhs>rhs, do NextMinus, see above for commentary */
  2631. if (DFISINF(dfl) && !DFISSIGNED(dfl)) { /* +Infinity special case */
  2632. DFSETNMAX(result);
  2633. return result;
  2634. }
  2635. saveround=set->round; /* save mode */
  2636. set->round=DEC_ROUND_FLOOR; /* .. round towards -Infinity */
  2637. deltatop=DECFLOAT_Sign; /* negative delta */
  2638. }
  2639. savestat=set->status; /* save status */
  2640. /* Here, Inexact is needed where appropriate (and hence Underflow, */
  2641. /* etc.). Therefore the tiny delta which is otherwise */
  2642. /* unrepresentable (see NextPlus and NextMinus) is constructed */
  2643. /* using the multiplication of FMA. */
  2644. decFloatZero(&delta); /* set up tiny delta */
  2645. DFWORD(&delta, DECWORDS-1)=1; /* coefficient=1 */
  2646. DFWORD(&delta, 0)=deltatop; /* Sign + biased exponent=0 */
  2647. decFloatFromString(&pointone, "1E-1", set); /* set up multiplier */
  2648. decFloatFMA(result, &delta, &pointone, dfl, set);
  2649. /* [Delta is truly tiny, so no need to correct sign of zero] */
  2650. /* use new status unless the result is normal */
  2651. if (decFloatIsNormal(result)) set->status=savestat; /* else goes forward */
  2652. set->round=saveround; /* restore mode */
  2653. return result;
  2654. } /* decFloatNextToward */
  2655. /* ------------------------------------------------------------------ */
  2656. /* decFloatOr -- logical digitwise OR of two decFloats */
  2657. /* */
  2658. /* result gets the result of ORing dfl and dfr */
  2659. /* dfl is the first decFloat (lhs) */
  2660. /* dfr is the second decFloat (rhs) */
  2661. /* set is the context */
  2662. /* returns result, which will be canonical with sign=0 */
  2663. /* */
  2664. /* The operands must be positive, finite with exponent q=0, and */
  2665. /* comprise just zeros and ones; if not, Invalid operation results. */
  2666. /* ------------------------------------------------------------------ */
  2667. decFloat * decFloatOr(decFloat *result,
  2668. const decFloat *dfl, const decFloat *dfr,
  2669. decContext *set) {
  2670. if (!DFISUINT01(dfl) || !DFISUINT01(dfr)
  2671. || !DFISCC01(dfl) || !DFISCC01(dfr)) return decInvalid(result, set);
  2672. /* the operands are positive finite integers (q=0) with just 0s and 1s */
  2673. #if DOUBLE
  2674. DFWORD(result, 0)=ZEROWORD
  2675. |((DFWORD(dfl, 0) | DFWORD(dfr, 0))&0x04009124);
  2676. DFWORD(result, 1)=(DFWORD(dfl, 1) | DFWORD(dfr, 1))&0x49124491;
  2677. #elif QUAD
  2678. DFWORD(result, 0)=ZEROWORD
  2679. |((DFWORD(dfl, 0) | DFWORD(dfr, 0))&0x04000912);
  2680. DFWORD(result, 1)=(DFWORD(dfl, 1) | DFWORD(dfr, 1))&0x44912449;
  2681. DFWORD(result, 2)=(DFWORD(dfl, 2) | DFWORD(dfr, 2))&0x12449124;
  2682. DFWORD(result, 3)=(DFWORD(dfl, 3) | DFWORD(dfr, 3))&0x49124491;
  2683. #endif
  2684. return result;
  2685. } /* decFloatOr */
  2686. /* ------------------------------------------------------------------ */
  2687. /* decFloatPlus -- add value to 0, heeding NaNs, etc. */
  2688. /* */
  2689. /* result gets the canonicalized 0+df */
  2690. /* df is the decFloat to plus */
  2691. /* set is the context */
  2692. /* returns result */
  2693. /* */
  2694. /* This has the same effect as 0+df where the exponent of the zero is */
  2695. /* the same as that of df (if df is finite). */
  2696. /* The effect is also the same as decFloatCopy except that NaNs */
  2697. /* are handled normally (the sign of a NaN is not affected, and an */
  2698. /* sNaN will signal), the result is canonical, and zero gets sign 0. */
  2699. /* ------------------------------------------------------------------ */
  2700. decFloat * decFloatPlus(decFloat *result, const decFloat *df,
  2701. decContext *set) {
  2702. if (DFISNAN(df)) return decNaNs(result, df, NULL, set);
  2703. decCanonical(result, df); /* copy and check */
  2704. if (DFISZERO(df)) DFBYTE(result, 0)&=~0x80; /* turn off sign bit */
  2705. return result;
  2706. } /* decFloatPlus */
  2707. /* ------------------------------------------------------------------ */
  2708. /* decFloatQuantize -- quantize a decFloat */
  2709. /* */
  2710. /* result gets the result of quantizing dfl to match dfr */
  2711. /* dfl is the first decFloat (lhs) */
  2712. /* dfr is the second decFloat (rhs), which sets the exponent */
  2713. /* set is the context */
  2714. /* returns result */
  2715. /* */
  2716. /* Unless there is an error or the result is infinite, the exponent */
  2717. /* of result is guaranteed to be the same as that of dfr. */
  2718. /* ------------------------------------------------------------------ */
  2719. decFloat * decFloatQuantize(decFloat *result,
  2720. const decFloat *dfl, const decFloat *dfr,
  2721. decContext *set) {
  2722. Int explb, exprb; /* left and right biased exponents */
  2723. uByte *ulsd; /* local LSD pointer */
  2724. uByte *ub, *uc; /* work */
  2725. Int drop; /* .. */
  2726. uInt dpd; /* .. */
  2727. uInt encode; /* encoding accumulator */
  2728. uInt sourhil, sourhir; /* top words from source decFloats */
  2729. uInt uiwork; /* for macros */
  2730. #if QUAD
  2731. uShort uswork; /* .. */
  2732. #endif
  2733. /* the following buffer holds the coefficient for manipulation */
  2734. uByte buf[4+DECPMAX*3+2*QUAD]; /* + space for zeros to left or right */
  2735. #if DECTRACE
  2736. bcdnum num; /* for trace displays */
  2737. #endif
  2738. /* Start decoding the arguments */
  2739. sourhil=DFWORD(dfl, 0); /* LHS top word */
  2740. explb=DECCOMBEXP[sourhil>>26]; /* get exponent high bits (in place) */
  2741. sourhir=DFWORD(dfr, 0); /* RHS top word */
  2742. exprb=DECCOMBEXP[sourhir>>26];
  2743. if (EXPISSPECIAL(explb | exprb)) { /* either is special? */
  2744. /* NaNs are handled as usual */
  2745. if (DFISNAN(dfl) || DFISNAN(dfr)) return decNaNs(result, dfl, dfr, set);
  2746. /* one infinity but not both is bad */
  2747. if (DFISINF(dfl)!=DFISINF(dfr)) return decInvalid(result, set);
  2748. /* both infinite; return canonical infinity with sign of LHS */
  2749. return decInfinity(result, dfl);
  2750. }
  2751. /* Here when both arguments are finite */
  2752. /* complete extraction of the exponents [no need to unbias] */
  2753. explb+=GETECON(dfl); /* + continuation */
  2754. exprb+=GETECON(dfr); /* .. */
  2755. /* calculate the number of digits to drop from the coefficient */
  2756. drop=exprb-explb; /* 0 if nothing to do */
  2757. if (drop==0) return decCanonical(result, dfl); /* return canonical */
  2758. /* the coefficient is needed; lay it out into buf, offset so zeros */
  2759. /* can be added before or after as needed -- an extra heading is */
  2760. /* added so can safely pad Quad DECPMAX-1 zeros to the left by */
  2761. /* fours */
  2762. #define BUFOFF (buf+4+DECPMAX)
  2763. GETCOEFF(dfl, BUFOFF); /* decode from decFloat */
  2764. /* [now the msd is at BUFOFF and the lsd is at BUFOFF+DECPMAX-1] */
  2765. #if DECTRACE
  2766. num.msd=BUFOFF;
  2767. num.lsd=BUFOFF+DECPMAX-1;
  2768. num.exponent=explb-DECBIAS;
  2769. num.sign=sourhil & DECFLOAT_Sign;
  2770. decShowNum(&num, "dfl");
  2771. #endif
  2772. if (drop>0) { /* [most common case] */
  2773. /* (this code is very similar to that in decFloatFinalize, but */
  2774. /* has many differences so is duplicated here -- so any changes */
  2775. /* may need to be made there, too) */
  2776. uByte *roundat; /* -> re-round digit */
  2777. uByte reround; /* reround value */
  2778. /* printf("Rounding; drop=%ld\n", (LI)drop); */
  2779. /* there is at least one zero needed to the left, in all but one */
  2780. /* exceptional (all-nines) case, so place four zeros now; this is */
  2781. /* needed almost always and makes rounding all-nines by fours safe */
  2782. UBFROMUI(BUFOFF-4, 0);
  2783. /* Three cases here: */
  2784. /* 1. new LSD is in coefficient (almost always) */
  2785. /* 2. new LSD is digit to left of coefficient (so MSD is */
  2786. /* round-for-reround digit) */
  2787. /* 3. new LSD is to left of case 2 (whole coefficient is sticky) */
  2788. /* Note that leading zeros can safely be treated as useful digits */
  2789. /* [duplicate check-stickies code to save a test] */
  2790. /* [by-digit check for stickies as runs of zeros are rare] */
  2791. if (drop<DECPMAX) { /* NB lengths not addresses */
  2792. roundat=BUFOFF+DECPMAX-drop;
  2793. reround=*roundat;
  2794. for (ub=roundat+1; ub<BUFOFF+DECPMAX; ub++) {
  2795. if (*ub!=0) { /* non-zero to be discarded */
  2796. reround=DECSTICKYTAB[reround]; /* apply sticky bit */
  2797. break; /* [remainder don't-care] */
  2798. }
  2799. } /* check stickies */
  2800. ulsd=roundat-1; /* set LSD */
  2801. }
  2802. else { /* edge case */
  2803. if (drop==DECPMAX) {
  2804. roundat=BUFOFF;
  2805. reround=*roundat;
  2806. }
  2807. else {
  2808. roundat=BUFOFF-1;
  2809. reround=0;
  2810. }
  2811. for (ub=roundat+1; ub<BUFOFF+DECPMAX; ub++) {
  2812. if (*ub!=0) { /* non-zero to be discarded */
  2813. reround=DECSTICKYTAB[reround]; /* apply sticky bit */
  2814. break; /* [remainder don't-care] */
  2815. }
  2816. } /* check stickies */
  2817. *BUFOFF=0; /* make a coefficient of 0 */
  2818. ulsd=BUFOFF; /* .. at the MSD place */
  2819. }
  2820. if (reround!=0) { /* discarding non-zero */
  2821. uInt bump=0;
  2822. set->status|=DEC_Inexact;
  2823. /* next decide whether to increment the coefficient */
  2824. if (set->round==DEC_ROUND_HALF_EVEN) { /* fastpath slowest case */
  2825. if (reround>5) bump=1; /* >0.5 goes up */
  2826. else if (reround==5) /* exactly 0.5000 .. */
  2827. bump=*ulsd & 0x01; /* .. up iff [new] lsd is odd */
  2828. } /* r-h-e */
  2829. else switch (set->round) {
  2830. case DEC_ROUND_DOWN: {
  2831. /* no change */
  2832. break;} /* r-d */
  2833. case DEC_ROUND_HALF_DOWN: {
  2834. if (reround>5) bump=1;
  2835. break;} /* r-h-d */
  2836. case DEC_ROUND_HALF_UP: {
  2837. if (reround>=5) bump=1;
  2838. break;} /* r-h-u */
  2839. case DEC_ROUND_UP: {
  2840. if (reround>0) bump=1;
  2841. break;} /* r-u */
  2842. case DEC_ROUND_CEILING: {
  2843. /* same as _UP for positive numbers, and as _DOWN for negatives */
  2844. if (!(sourhil&DECFLOAT_Sign) && reround>0) bump=1;
  2845. break;} /* r-c */
  2846. case DEC_ROUND_FLOOR: {
  2847. /* same as _UP for negative numbers, and as _DOWN for positive */
  2848. /* [negative reround cannot occur on 0] */
  2849. if (sourhil&DECFLOAT_Sign && reround>0) bump=1;
  2850. break;} /* r-f */
  2851. case DEC_ROUND_05UP: {
  2852. if (reround>0) { /* anything out there is 'sticky' */
  2853. /* bump iff lsd=0 or 5; this cannot carry so it could be */
  2854. /* effected immediately with no bump -- but the code */
  2855. /* is clearer if this is done the same way as the others */
  2856. if (*ulsd==0 || *ulsd==5) bump=1;
  2857. }
  2858. break;} /* r-r */
  2859. default: { /* e.g., DEC_ROUND_MAX */
  2860. set->status|=DEC_Invalid_context;
  2861. #if DECCHECK
  2862. printf("Unknown rounding mode: %ld\n", (LI)set->round);
  2863. #endif
  2864. break;}
  2865. } /* switch (not r-h-e) */
  2866. /* printf("ReRound: %ld bump: %ld\n", (LI)reround, (LI)bump); */
  2867. if (bump!=0) { /* need increment */
  2868. /* increment the coefficient; this could give 1000... (after */
  2869. /* the all nines case) */
  2870. ub=ulsd;
  2871. for (; UBTOUI(ub-3)==0x09090909; ub-=4) UBFROMUI(ub-3, 0);
  2872. /* now at most 3 digits left to non-9 (usually just the one) */
  2873. for (; *ub==9; ub--) *ub=0;
  2874. *ub+=1;
  2875. /* [the all-nines case will have carried one digit to the */
  2876. /* left of the original MSD -- just where it is needed] */
  2877. } /* bump needed */
  2878. } /* inexact rounding */
  2879. /* now clear zeros to the left so exactly DECPMAX digits will be */
  2880. /* available in the coefficent -- the first word to the left was */
  2881. /* cleared earlier for safe carry; now add any more needed */
  2882. if (drop>4) {
  2883. UBFROMUI(BUFOFF-8, 0); /* must be at least 5 */
  2884. for (uc=BUFOFF-12; uc>ulsd-DECPMAX-3; uc-=4) UBFROMUI(uc, 0);
  2885. }
  2886. } /* need round (drop>0) */
  2887. else { /* drop<0; padding with -drop digits is needed */
  2888. /* This is the case where an error can occur if the padded */
  2889. /* coefficient will not fit; checking for this can be done in the */
  2890. /* same loop as padding for zeros if the no-hope and zero cases */
  2891. /* are checked first */
  2892. if (-drop>DECPMAX-1) { /* cannot fit unless 0 */
  2893. if (!ISCOEFFZERO(BUFOFF)) return decInvalid(result, set);
  2894. /* a zero can have any exponent; just drop through and use it */
  2895. ulsd=BUFOFF+DECPMAX-1;
  2896. }
  2897. else { /* padding will fit (but may still be too long) */
  2898. /* final-word mask depends on endianess */
  2899. #if DECLITEND
  2900. static const uInt dmask[]={0, 0x000000ff, 0x0000ffff, 0x00ffffff};
  2901. #else
  2902. static const uInt dmask[]={0, 0xff000000, 0xffff0000, 0xffffff00};
  2903. #endif
  2904. /* note that here zeros to the right are added by fours, so in */
  2905. /* the Quad case this could write 36 zeros if the coefficient has */
  2906. /* fewer than three significant digits (hence the +2*QUAD for buf) */
  2907. for (uc=BUFOFF+DECPMAX;; uc+=4) {
  2908. UBFROMUI(uc, 0);
  2909. if (UBTOUI(uc-DECPMAX)!=0) { /* could be bad */
  2910. /* if all four digits should be zero, definitely bad */
  2911. if (uc<=BUFOFF+DECPMAX+(-drop)-4)
  2912. return decInvalid(result, set);
  2913. /* must be a 1- to 3-digit sequence; check more carefully */
  2914. if ((UBTOUI(uc-DECPMAX)&dmask[(-drop)%4])!=0)
  2915. return decInvalid(result, set);
  2916. break; /* no need for loop end test */
  2917. }
  2918. if (uc>=BUFOFF+DECPMAX+(-drop)-4) break; /* done */
  2919. }
  2920. ulsd=BUFOFF+DECPMAX+(-drop)-1;
  2921. } /* pad and check leading zeros */
  2922. } /* drop<0 */
  2923. #if DECTRACE
  2924. num.msd=ulsd-DECPMAX+1;
  2925. num.lsd=ulsd;
  2926. num.exponent=explb-DECBIAS;
  2927. num.sign=sourhil & DECFLOAT_Sign;
  2928. decShowNum(&num, "res");
  2929. #endif
  2930. /*------------------------------------------------------------------*/
  2931. /* At this point the result is DECPMAX digits, ending at ulsd, so */
  2932. /* fits the encoding exactly; there is no possibility of error */
  2933. /*------------------------------------------------------------------*/
  2934. encode=((exprb>>DECECONL)<<4) + *(ulsd-DECPMAX+1); /* make index */
  2935. encode=DECCOMBFROM[encode]; /* indexed by (0-2)*16+msd */
  2936. /* the exponent continuation can be extracted from the original RHS */
  2937. encode|=sourhir & ECONMASK;
  2938. encode|=sourhil&DECFLOAT_Sign; /* add the sign from LHS */
  2939. /* finally encode the coefficient */
  2940. /* private macro to encode a declet; this version can be used */
  2941. /* because all coefficient digits exist */
  2942. #define getDPD3q(dpd, n) ub=ulsd-(3*(n))-2; \
  2943. dpd=BCD2DPD[(*ub*256)+(*(ub+1)*16)+*(ub+2)];
  2944. #if DOUBLE
  2945. getDPD3q(dpd, 4); encode|=dpd<<8;
  2946. getDPD3q(dpd, 3); encode|=dpd>>2;
  2947. DFWORD(result, 0)=encode;
  2948. encode=dpd<<30;
  2949. getDPD3q(dpd, 2); encode|=dpd<<20;
  2950. getDPD3q(dpd, 1); encode|=dpd<<10;
  2951. getDPD3q(dpd, 0); encode|=dpd;
  2952. DFWORD(result, 1)=encode;
  2953. #elif QUAD
  2954. getDPD3q(dpd,10); encode|=dpd<<4;
  2955. getDPD3q(dpd, 9); encode|=dpd>>6;
  2956. DFWORD(result, 0)=encode;
  2957. encode=dpd<<26;
  2958. getDPD3q(dpd, 8); encode|=dpd<<16;
  2959. getDPD3q(dpd, 7); encode|=dpd<<6;
  2960. getDPD3q(dpd, 6); encode|=dpd>>4;
  2961. DFWORD(result, 1)=encode;
  2962. encode=dpd<<28;
  2963. getDPD3q(dpd, 5); encode|=dpd<<18;
  2964. getDPD3q(dpd, 4); encode|=dpd<<8;
  2965. getDPD3q(dpd, 3); encode|=dpd>>2;
  2966. DFWORD(result, 2)=encode;
  2967. encode=dpd<<30;
  2968. getDPD3q(dpd, 2); encode|=dpd<<20;
  2969. getDPD3q(dpd, 1); encode|=dpd<<10;
  2970. getDPD3q(dpd, 0); encode|=dpd;
  2971. DFWORD(result, 3)=encode;
  2972. #endif
  2973. return result;
  2974. } /* decFloatQuantize */
  2975. /* ------------------------------------------------------------------ */
  2976. /* decFloatReduce -- reduce finite coefficient to minimum length */
  2977. /* */
  2978. /* result gets the reduced decFloat */
  2979. /* df is the source decFloat */
  2980. /* set is the context */
  2981. /* returns result, which will be canonical */
  2982. /* */
  2983. /* This removes all possible trailing zeros from the coefficient; */
  2984. /* some may remain when the number is very close to Nmax. */
  2985. /* Special values are unchanged and no status is set unless df=sNaN. */
  2986. /* Reduced zero has an exponent q=0. */
  2987. /* ------------------------------------------------------------------ */
  2988. decFloat * decFloatReduce(decFloat *result, const decFloat *df,
  2989. decContext *set) {
  2990. bcdnum num; /* work */
  2991. uByte buf[DECPMAX], *ub; /* coefficient and pointer */
  2992. if (df!=result) *result=*df; /* copy, if needed */
  2993. if (DFISNAN(df)) return decNaNs(result, df, NULL, set); /* sNaN */
  2994. /* zeros and infinites propagate too */
  2995. if (DFISINF(df)) return decInfinity(result, df); /* canonical */
  2996. if (DFISZERO(df)) {
  2997. uInt sign=DFWORD(df, 0)&DECFLOAT_Sign;
  2998. decFloatZero(result);
  2999. DFWORD(result, 0)|=sign;
  3000. return result; /* exponent dropped, sign OK */
  3001. }
  3002. /* non-zero finite */
  3003. GETCOEFF(df, buf);
  3004. ub=buf+DECPMAX-1; /* -> lsd */
  3005. if (*ub) return result; /* no trailing zeros */
  3006. for (ub--; *ub==0;) ub--; /* terminates because non-zero */
  3007. /* *ub is the first non-zero from the right */
  3008. num.sign=DFWORD(df, 0)&DECFLOAT_Sign; /* set up number... */
  3009. num.exponent=GETEXPUN(df)+(Int)(buf+DECPMAX-1-ub); /* adjusted exponent */
  3010. num.msd=buf;
  3011. num.lsd=ub;
  3012. return decFinalize(result, &num, set);
  3013. } /* decFloatReduce */
  3014. /* ------------------------------------------------------------------ */
  3015. /* decFloatRemainder -- integer divide and return remainder */
  3016. /* */
  3017. /* result gets the remainder of dividing dfl by dfr: */
  3018. /* dfl is the first decFloat (lhs) */
  3019. /* dfr is the second decFloat (rhs) */
  3020. /* set is the context */
  3021. /* returns result */
  3022. /* */
  3023. /* ------------------------------------------------------------------ */
  3024. decFloat * decFloatRemainder(decFloat *result,
  3025. const decFloat *dfl, const decFloat *dfr,
  3026. decContext *set) {
  3027. return decDivide(result, dfl, dfr, set, REMAINDER);
  3028. } /* decFloatRemainder */
  3029. /* ------------------------------------------------------------------ */
  3030. /* decFloatRemainderNear -- integer divide to nearest and remainder */
  3031. /* */
  3032. /* result gets the remainder of dividing dfl by dfr: */
  3033. /* dfl is the first decFloat (lhs) */
  3034. /* dfr is the second decFloat (rhs) */
  3035. /* set is the context */
  3036. /* returns result */
  3037. /* */
  3038. /* This is the IEEE remainder, where the nearest integer is used. */
  3039. /* ------------------------------------------------------------------ */
  3040. decFloat * decFloatRemainderNear(decFloat *result,
  3041. const decFloat *dfl, const decFloat *dfr,
  3042. decContext *set) {
  3043. return decDivide(result, dfl, dfr, set, REMNEAR);
  3044. } /* decFloatRemainderNear */
  3045. /* ------------------------------------------------------------------ */
  3046. /* decFloatRotate -- rotate the coefficient of a decFloat left/right */
  3047. /* */
  3048. /* result gets the result of rotating dfl */
  3049. /* dfl is the source decFloat to rotate */
  3050. /* dfr is the count of digits to rotate, an integer (with q=0) */
  3051. /* set is the context */
  3052. /* returns result */
  3053. /* */
  3054. /* The digits of the coefficient of dfl are rotated to the left (if */
  3055. /* dfr is positive) or to the right (if dfr is negative) without */
  3056. /* adjusting the exponent or the sign of dfl. */
  3057. /* */
  3058. /* dfr must be in the range -DECPMAX through +DECPMAX. */
  3059. /* NaNs are propagated as usual. An infinite dfl is unaffected (but */
  3060. /* dfr must be valid). No status is set unless dfr is invalid or an */
  3061. /* operand is an sNaN. The result is canonical. */
  3062. /* ------------------------------------------------------------------ */
  3063. #define PHALF (ROUNDUP(DECPMAX/2, 4)) /* half length, rounded up */
  3064. decFloat * decFloatRotate(decFloat *result,
  3065. const decFloat *dfl, const decFloat *dfr,
  3066. decContext *set) {
  3067. Int rotate; /* dfr as an Int */
  3068. uByte buf[DECPMAX+PHALF]; /* coefficient + half */
  3069. uInt digits, savestat; /* work */
  3070. bcdnum num; /* .. */
  3071. uByte *ub; /* .. */
  3072. if (DFISNAN(dfl)||DFISNAN(dfr)) return decNaNs(result, dfl, dfr, set);
  3073. if (!DFISINT(dfr)) return decInvalid(result, set);
  3074. digits=decFloatDigits(dfr); /* calculate digits */
  3075. if (digits>2) return decInvalid(result, set); /* definitely out of range */
  3076. rotate=DPD2BIN[DFWORD(dfr, DECWORDS-1)&0x3ff]; /* is in bottom declet */
  3077. if (rotate>DECPMAX) return decInvalid(result, set); /* too big */
  3078. /* [from here on no error or status change is possible] */
  3079. if (DFISINF(dfl)) return decInfinity(result, dfl); /* canonical */
  3080. /* handle no-rotate cases */
  3081. if (rotate==0 || rotate==DECPMAX) return decCanonical(result, dfl);
  3082. /* a real rotate is needed: 0 < rotate < DECPMAX */
  3083. /* reduce the rotation to no more than half to reduce copying later */
  3084. /* (for QUAD in fact half + 2 digits) */
  3085. if (DFISSIGNED(dfr)) rotate=-rotate;
  3086. if (abs(rotate)>PHALF) {
  3087. if (rotate<0) rotate=DECPMAX+rotate;
  3088. else rotate=rotate-DECPMAX;
  3089. }
  3090. /* now lay out the coefficient, leaving room to the right or the */
  3091. /* left depending on the direction of rotation */
  3092. ub=buf;
  3093. if (rotate<0) ub+=PHALF; /* rotate right, so space to left */
  3094. GETCOEFF(dfl, ub);
  3095. /* copy half the digits to left or right, and set num.msd */
  3096. if (rotate<0) {
  3097. memcpy(buf, buf+DECPMAX, PHALF);
  3098. num.msd=buf+PHALF+rotate;
  3099. }
  3100. else {
  3101. memcpy(buf+DECPMAX, buf, PHALF);
  3102. num.msd=buf+rotate;
  3103. }
  3104. /* fill in rest of num */
  3105. num.lsd=num.msd+DECPMAX-1;
  3106. num.sign=DFWORD(dfl, 0)&DECFLOAT_Sign;
  3107. num.exponent=GETEXPUN(dfl);
  3108. savestat=set->status; /* record */
  3109. decFinalize(result, &num, set);
  3110. set->status=savestat; /* restore */
  3111. return result;
  3112. } /* decFloatRotate */
  3113. /* ------------------------------------------------------------------ */
  3114. /* decFloatSameQuantum -- test decFloats for same quantum */
  3115. /* */
  3116. /* dfl is the first decFloat (lhs) */
  3117. /* dfr is the second decFloat (rhs) */
  3118. /* returns 1 if the operands have the same quantum, 0 otherwise */
  3119. /* */
  3120. /* No error is possible and no status results. */
  3121. /* ------------------------------------------------------------------ */
  3122. uInt decFloatSameQuantum(const decFloat *dfl, const decFloat *dfr) {
  3123. if (DFISSPECIAL(dfl) || DFISSPECIAL(dfr)) {
  3124. if (DFISNAN(dfl) && DFISNAN(dfr)) return 1;
  3125. if (DFISINF(dfl) && DFISINF(dfr)) return 1;
  3126. return 0; /* any other special mixture gives false */
  3127. }
  3128. if (GETEXP(dfl)==GETEXP(dfr)) return 1; /* biased exponents match */
  3129. return 0;
  3130. } /* decFloatSameQuantum */
  3131. /* ------------------------------------------------------------------ */
  3132. /* decFloatScaleB -- multiply by a power of 10, as per 754 */
  3133. /* */
  3134. /* result gets the result of the operation */
  3135. /* dfl is the first decFloat (lhs) */
  3136. /* dfr is the second decFloat (rhs), am integer (with q=0) */
  3137. /* set is the context */
  3138. /* returns result */
  3139. /* */
  3140. /* This computes result=dfl x 10**dfr where dfr is an integer in the */
  3141. /* range +/-2*(emax+pmax), typically resulting from LogB. */
  3142. /* Underflow and Overflow (with Inexact) may occur. NaNs propagate */
  3143. /* as usual. */
  3144. /* ------------------------------------------------------------------ */
  3145. #define SCALEBMAX 2*(DECEMAX+DECPMAX) /* D=800, Q=12356 */
  3146. decFloat * decFloatScaleB(decFloat *result,
  3147. const decFloat *dfl, const decFloat *dfr,
  3148. decContext *set) {
  3149. uInt digits; /* work */
  3150. Int expr; /* dfr as an Int */
  3151. if (DFISNAN(dfl)||DFISNAN(dfr)) return decNaNs(result, dfl, dfr, set);
  3152. if (!DFISINT(dfr)) return decInvalid(result, set);
  3153. digits=decFloatDigits(dfr); /* calculate digits */
  3154. #if DOUBLE
  3155. if (digits>3) return decInvalid(result, set); /* definitely out of range */
  3156. expr=DPD2BIN[DFWORD(dfr, 1)&0x3ff]; /* must be in bottom declet */
  3157. #elif QUAD
  3158. if (digits>5) return decInvalid(result, set); /* definitely out of range */
  3159. expr=DPD2BIN[DFWORD(dfr, 3)&0x3ff] /* in bottom 2 declets .. */
  3160. +DPD2BIN[(DFWORD(dfr, 3)>>10)&0x3ff]*1000; /* .. */
  3161. #endif
  3162. if (expr>SCALEBMAX) return decInvalid(result, set); /* oops */
  3163. /* [from now on no error possible] */
  3164. if (DFISINF(dfl)) return decInfinity(result, dfl); /* canonical */
  3165. if (DFISSIGNED(dfr)) expr=-expr;
  3166. /* dfl is finite and expr is valid */
  3167. *result=*dfl; /* copy to target */
  3168. return decFloatSetExponent(result, set, GETEXPUN(result)+expr);
  3169. } /* decFloatScaleB */
  3170. /* ------------------------------------------------------------------ */
  3171. /* decFloatShift -- shift the coefficient of a decFloat left or right */
  3172. /* */
  3173. /* result gets the result of shifting dfl */
  3174. /* dfl is the source decFloat to shift */
  3175. /* dfr is the count of digits to shift, an integer (with q=0) */
  3176. /* set is the context */
  3177. /* returns result */
  3178. /* */
  3179. /* The digits of the coefficient of dfl are shifted to the left (if */
  3180. /* dfr is positive) or to the right (if dfr is negative) without */
  3181. /* adjusting the exponent or the sign of dfl. */
  3182. /* */
  3183. /* dfr must be in the range -DECPMAX through +DECPMAX. */
  3184. /* NaNs are propagated as usual. An infinite dfl is unaffected (but */
  3185. /* dfr must be valid). No status is set unless dfr is invalid or an */
  3186. /* operand is an sNaN. The result is canonical. */
  3187. /* ------------------------------------------------------------------ */
  3188. decFloat * decFloatShift(decFloat *result,
  3189. const decFloat *dfl, const decFloat *dfr,
  3190. decContext *set) {
  3191. Int shift; /* dfr as an Int */
  3192. uByte buf[DECPMAX*2]; /* coefficient + padding */
  3193. uInt digits, savestat; /* work */
  3194. bcdnum num; /* .. */
  3195. uInt uiwork; /* for macros */
  3196. if (DFISNAN(dfl)||DFISNAN(dfr)) return decNaNs(result, dfl, dfr, set);
  3197. if (!DFISINT(dfr)) return decInvalid(result, set);
  3198. digits=decFloatDigits(dfr); /* calculate digits */
  3199. if (digits>2) return decInvalid(result, set); /* definitely out of range */
  3200. shift=DPD2BIN[DFWORD(dfr, DECWORDS-1)&0x3ff]; /* is in bottom declet */
  3201. if (shift>DECPMAX) return decInvalid(result, set); /* too big */
  3202. /* [from here on no error or status change is possible] */
  3203. if (DFISINF(dfl)) return decInfinity(result, dfl); /* canonical */
  3204. /* handle no-shift and all-shift (clear to zero) cases */
  3205. if (shift==0) return decCanonical(result, dfl);
  3206. if (shift==DECPMAX) { /* zero with sign */
  3207. uByte sign=(uByte)(DFBYTE(dfl, 0)&0x80); /* save sign bit */
  3208. decFloatZero(result); /* make +0 */
  3209. DFBYTE(result, 0)=(uByte)(DFBYTE(result, 0)|sign); /* and set sign */
  3210. /* [cannot safely use CopySign] */
  3211. return result;
  3212. }
  3213. /* a real shift is needed: 0 < shift < DECPMAX */
  3214. num.sign=DFWORD(dfl, 0)&DECFLOAT_Sign;
  3215. num.exponent=GETEXPUN(dfl);
  3216. num.msd=buf;
  3217. GETCOEFF(dfl, buf);
  3218. if (DFISSIGNED(dfr)) { /* shift right */
  3219. /* edge cases are taken care of, so this is easy */
  3220. num.lsd=buf+DECPMAX-shift-1;
  3221. }
  3222. else { /* shift left -- zero padding needed to right */
  3223. UBFROMUI(buf+DECPMAX, 0); /* 8 will handle most cases */
  3224. UBFROMUI(buf+DECPMAX+4, 0); /* .. */
  3225. if (shift>8) memset(buf+DECPMAX+8, 0, 8+QUAD*18); /* all other cases */
  3226. num.msd+=shift;
  3227. num.lsd=num.msd+DECPMAX-1;
  3228. }
  3229. savestat=set->status; /* record */
  3230. decFinalize(result, &num, set);
  3231. set->status=savestat; /* restore */
  3232. return result;
  3233. } /* decFloatShift */
  3234. /* ------------------------------------------------------------------ */
  3235. /* decFloatSubtract -- subtract a decFloat from another */
  3236. /* */
  3237. /* result gets the result of subtracting dfr from dfl: */
  3238. /* dfl is the first decFloat (lhs) */
  3239. /* dfr is the second decFloat (rhs) */
  3240. /* set is the context */
  3241. /* returns result */
  3242. /* */
  3243. /* ------------------------------------------------------------------ */
  3244. decFloat * decFloatSubtract(decFloat *result,
  3245. const decFloat *dfl, const decFloat *dfr,
  3246. decContext *set) {
  3247. decFloat temp;
  3248. /* NaNs must propagate without sign change */
  3249. if (DFISNAN(dfr)) return decFloatAdd(result, dfl, dfr, set);
  3250. temp=*dfr; /* make a copy */
  3251. DFBYTE(&temp, 0)^=0x80; /* flip sign */
  3252. return decFloatAdd(result, dfl, &temp, set); /* and add to the lhs */
  3253. } /* decFloatSubtract */
  3254. /* ------------------------------------------------------------------ */
  3255. /* decFloatToInt -- round to 32-bit binary integer (4 flavours) */
  3256. /* */
  3257. /* df is the decFloat to round */
  3258. /* set is the context */
  3259. /* round is the rounding mode to use */
  3260. /* returns a uInt or an Int, rounded according to the name */
  3261. /* */
  3262. /* Invalid will always be signaled if df is a NaN, is Infinite, or is */
  3263. /* outside the range of the target; Inexact will not be signaled for */
  3264. /* simple rounding unless 'Exact' appears in the name. */
  3265. /* ------------------------------------------------------------------ */
  3266. uInt decFloatToUInt32(const decFloat *df, decContext *set,
  3267. enum rounding round) {
  3268. return decToInt32(df, set, round, 0, 1);}
  3269. uInt decFloatToUInt32Exact(const decFloat *df, decContext *set,
  3270. enum rounding round) {
  3271. return decToInt32(df, set, round, 1, 1);}
  3272. Int decFloatToInt32(const decFloat *df, decContext *set,
  3273. enum rounding round) {
  3274. return (Int)decToInt32(df, set, round, 0, 0);}
  3275. Int decFloatToInt32Exact(const decFloat *df, decContext *set,
  3276. enum rounding round) {
  3277. return (Int)decToInt32(df, set, round, 1, 0);}
  3278. /* ------------------------------------------------------------------ */
  3279. /* decFloatToIntegral -- round to integral value (two flavours) */
  3280. /* */
  3281. /* result gets the result */
  3282. /* df is the decFloat to round */
  3283. /* set is the context */
  3284. /* round is the rounding mode to use */
  3285. /* returns result */
  3286. /* */
  3287. /* No exceptions, even Inexact, are raised except for sNaN input, or */
  3288. /* if 'Exact' appears in the name. */
  3289. /* ------------------------------------------------------------------ */
  3290. decFloat * decFloatToIntegralValue(decFloat *result, const decFloat *df,
  3291. decContext *set, enum rounding round) {
  3292. return decToIntegral(result, df, set, round, 0);}
  3293. decFloat * decFloatToIntegralExact(decFloat *result, const decFloat *df,
  3294. decContext *set) {
  3295. return decToIntegral(result, df, set, set->round, 1);}
  3296. /* ------------------------------------------------------------------ */
  3297. /* decFloatXor -- logical digitwise XOR of two decFloats */
  3298. /* */
  3299. /* result gets the result of XORing dfl and dfr */
  3300. /* dfl is the first decFloat (lhs) */
  3301. /* dfr is the second decFloat (rhs) */
  3302. /* set is the context */
  3303. /* returns result, which will be canonical with sign=0 */
  3304. /* */
  3305. /* The operands must be positive, finite with exponent q=0, and */
  3306. /* comprise just zeros and ones; if not, Invalid operation results. */
  3307. /* ------------------------------------------------------------------ */
  3308. decFloat * decFloatXor(decFloat *result,
  3309. const decFloat *dfl, const decFloat *dfr,
  3310. decContext *set) {
  3311. if (!DFISUINT01(dfl) || !DFISUINT01(dfr)
  3312. || !DFISCC01(dfl) || !DFISCC01(dfr)) return decInvalid(result, set);
  3313. /* the operands are positive finite integers (q=0) with just 0s and 1s */
  3314. #if DOUBLE
  3315. DFWORD(result, 0)=ZEROWORD
  3316. |((DFWORD(dfl, 0) ^ DFWORD(dfr, 0))&0x04009124);
  3317. DFWORD(result, 1)=(DFWORD(dfl, 1) ^ DFWORD(dfr, 1))&0x49124491;
  3318. #elif QUAD
  3319. DFWORD(result, 0)=ZEROWORD
  3320. |((DFWORD(dfl, 0) ^ DFWORD(dfr, 0))&0x04000912);
  3321. DFWORD(result, 1)=(DFWORD(dfl, 1) ^ DFWORD(dfr, 1))&0x44912449;
  3322. DFWORD(result, 2)=(DFWORD(dfl, 2) ^ DFWORD(dfr, 2))&0x12449124;
  3323. DFWORD(result, 3)=(DFWORD(dfl, 3) ^ DFWORD(dfr, 3))&0x49124491;
  3324. #endif
  3325. return result;
  3326. } /* decFloatXor */
  3327. /* ------------------------------------------------------------------ */
  3328. /* decInvalid -- set Invalid_operation result */
  3329. /* */
  3330. /* result gets a canonical NaN */
  3331. /* set is the context */
  3332. /* returns result */
  3333. /* */
  3334. /* status has Invalid_operation added */
  3335. /* ------------------------------------------------------------------ */
  3336. static decFloat *decInvalid(decFloat *result, decContext *set) {
  3337. decFloatZero(result);
  3338. DFWORD(result, 0)=DECFLOAT_qNaN;
  3339. set->status|=DEC_Invalid_operation;
  3340. return result;
  3341. } /* decInvalid */
  3342. /* ------------------------------------------------------------------ */
  3343. /* decInfinity -- set canonical Infinity with sign from a decFloat */
  3344. /* */
  3345. /* result gets a canonical Infinity */
  3346. /* df is source decFloat (only the sign is used) */
  3347. /* returns result */
  3348. /* */
  3349. /* df may be the same as result */
  3350. /* ------------------------------------------------------------------ */
  3351. static decFloat *decInfinity(decFloat *result, const decFloat *df) {
  3352. uInt sign=DFWORD(df, 0); /* save source signword */
  3353. decFloatZero(result); /* clear everything */
  3354. DFWORD(result, 0)=DECFLOAT_Inf | (sign & DECFLOAT_Sign);
  3355. return result;
  3356. } /* decInfinity */
  3357. /* ------------------------------------------------------------------ */
  3358. /* decNaNs -- handle NaN argument(s) */
  3359. /* */
  3360. /* result gets the result of handling dfl and dfr, one or both of */
  3361. /* which is a NaN */
  3362. /* dfl is the first decFloat (lhs) */
  3363. /* dfr is the second decFloat (rhs) -- may be NULL for a single- */
  3364. /* operand operation */
  3365. /* set is the context */
  3366. /* returns result */
  3367. /* */
  3368. /* Called when one or both operands is a NaN, and propagates the */
  3369. /* appropriate result to res. When an sNaN is found, it is changed */
  3370. /* to a qNaN and Invalid operation is set. */
  3371. /* ------------------------------------------------------------------ */
  3372. static decFloat *decNaNs(decFloat *result,
  3373. const decFloat *dfl, const decFloat *dfr,
  3374. decContext *set) {
  3375. /* handle sNaNs first */
  3376. if (dfr!=NULL && DFISSNAN(dfr) && !DFISSNAN(dfl)) dfl=dfr; /* use RHS */
  3377. if (DFISSNAN(dfl)) {
  3378. decCanonical(result, dfl); /* propagate canonical sNaN */
  3379. DFWORD(result, 0)&=~(DECFLOAT_qNaN ^ DECFLOAT_sNaN); /* quiet */
  3380. set->status|=DEC_Invalid_operation;
  3381. return result;
  3382. }
  3383. /* one or both is a quiet NaN */
  3384. if (!DFISNAN(dfl)) dfl=dfr; /* RHS must be NaN, use it */
  3385. return decCanonical(result, dfl); /* propagate canonical qNaN */
  3386. } /* decNaNs */
  3387. /* ------------------------------------------------------------------ */
  3388. /* decNumCompare -- numeric comparison of two decFloats */
  3389. /* */
  3390. /* dfl is the left-hand decFloat, which is not a NaN */
  3391. /* dfr is the right-hand decFloat, which is not a NaN */
  3392. /* tot is 1 for total order compare, 0 for simple numeric */
  3393. /* returns -1, 0, or +1 for dfl<dfr, dfl=dfr, dfl>dfr */
  3394. /* */
  3395. /* No error is possible; status and mode are unchanged. */
  3396. /* ------------------------------------------------------------------ */
  3397. static Int decNumCompare(const decFloat *dfl, const decFloat *dfr, Flag tot) {
  3398. Int sigl, sigr; /* LHS and RHS non-0 signums */
  3399. Int shift; /* shift needed to align operands */
  3400. uByte *ub, *uc; /* work */
  3401. uInt uiwork; /* for macros */
  3402. /* buffers +2 if Quad (36 digits), need double plus 4 for safe padding */
  3403. uByte bufl[DECPMAX*2+QUAD*2+4]; /* for LHS coefficient + padding */
  3404. uByte bufr[DECPMAX*2+QUAD*2+4]; /* for RHS coefficient + padding */
  3405. sigl=1;
  3406. if (DFISSIGNED(dfl)) {
  3407. if (!DFISSIGNED(dfr)) { /* -LHS +RHS */
  3408. if (DFISZERO(dfl) && DFISZERO(dfr) && !tot) return 0;
  3409. return -1; /* RHS wins */
  3410. }
  3411. sigl=-1;
  3412. }
  3413. if (DFISSIGNED(dfr)) {
  3414. if (!DFISSIGNED(dfl)) { /* +LHS -RHS */
  3415. if (DFISZERO(dfl) && DFISZERO(dfr) && !tot) return 0;
  3416. return +1; /* LHS wins */
  3417. }
  3418. }
  3419. /* signs are the same; operand(s) could be zero */
  3420. sigr=-sigl; /* sign to return if abs(RHS) wins */
  3421. if (DFISINF(dfl)) {
  3422. if (DFISINF(dfr)) return 0; /* both infinite & same sign */
  3423. return sigl; /* inf > n */
  3424. }
  3425. if (DFISINF(dfr)) return sigr; /* n < inf [dfl is finite] */
  3426. /* here, both are same sign and finite; calculate their offset */
  3427. shift=GETEXP(dfl)-GETEXP(dfr); /* [0 means aligned] */
  3428. /* [bias can be ignored -- the absolute exponent is not relevant] */
  3429. if (DFISZERO(dfl)) {
  3430. if (!DFISZERO(dfr)) return sigr; /* LHS=0, RHS!=0 */
  3431. /* both are zero, return 0 if both same exponent or numeric compare */
  3432. if (shift==0 || !tot) return 0;
  3433. if (shift>0) return sigl;
  3434. return sigr; /* [shift<0] */
  3435. }
  3436. else { /* LHS!=0 */
  3437. if (DFISZERO(dfr)) return sigl; /* LHS!=0, RHS=0 */
  3438. }
  3439. /* both are known to be non-zero at this point */
  3440. /* if the exponents are so different that the coefficients do not */
  3441. /* overlap (by even one digit) then a full comparison is not needed */
  3442. if (abs(shift)>=DECPMAX) { /* no overlap */
  3443. /* coefficients are known to be non-zero */
  3444. if (shift>0) return sigl;
  3445. return sigr; /* [shift<0] */
  3446. }
  3447. /* decode the coefficients */
  3448. /* (shift both right two if Quad to make a multiple of four) */
  3449. #if QUAD
  3450. UBFROMUI(bufl, 0);
  3451. UBFROMUI(bufr, 0);
  3452. #endif
  3453. GETCOEFF(dfl, bufl+QUAD*2); /* decode from decFloat */
  3454. GETCOEFF(dfr, bufr+QUAD*2); /* .. */
  3455. if (shift==0) { /* aligned; common and easy */
  3456. /* all multiples of four, here */
  3457. for (ub=bufl, uc=bufr; ub<bufl+DECPMAX+QUAD*2; ub+=4, uc+=4) {
  3458. uInt ui=UBTOUI(ub);
  3459. if (ui==UBTOUI(uc)) continue; /* so far so same */
  3460. /* about to find a winner; go by bytes in case little-endian */
  3461. for (;; ub++, uc++) {
  3462. if (*ub>*uc) return sigl; /* difference found */
  3463. if (*ub<*uc) return sigr; /* .. */
  3464. }
  3465. }
  3466. } /* aligned */
  3467. else if (shift>0) { /* lhs to left */
  3468. ub=bufl; /* RHS pointer */
  3469. /* pad bufl so right-aligned; most shifts will fit in 8 */
  3470. UBFROMUI(bufl+DECPMAX+QUAD*2, 0); /* add eight zeros */
  3471. UBFROMUI(bufl+DECPMAX+QUAD*2+4, 0); /* .. */
  3472. if (shift>8) {
  3473. /* more than eight; fill the rest, and also worth doing the */
  3474. /* lead-in by fours */
  3475. uByte *up; /* work */
  3476. uByte *upend=bufl+DECPMAX+QUAD*2+shift;
  3477. for (up=bufl+DECPMAX+QUAD*2+8; up<upend; up+=4) UBFROMUI(up, 0);
  3478. /* [pads up to 36 in all for Quad] */
  3479. for (;; ub+=4) {
  3480. if (UBTOUI(ub)!=0) return sigl;
  3481. if (ub+4>bufl+shift-4) break;
  3482. }
  3483. }
  3484. /* check remaining leading digits */
  3485. for (; ub<bufl+shift; ub++) if (*ub!=0) return sigl;
  3486. /* now start the overlapped part; bufl has been padded, so the */
  3487. /* comparison can go for the full length of bufr, which is a */
  3488. /* multiple of 4 bytes */
  3489. for (uc=bufr; ; uc+=4, ub+=4) {
  3490. uInt ui=UBTOUI(ub);
  3491. if (ui!=UBTOUI(uc)) { /* mismatch found */
  3492. for (;; uc++, ub++) { /* check from left [little-endian?] */
  3493. if (*ub>*uc) return sigl; /* difference found */
  3494. if (*ub<*uc) return sigr; /* .. */
  3495. }
  3496. } /* mismatch */
  3497. if (uc==bufr+QUAD*2+DECPMAX-4) break; /* all checked */
  3498. }
  3499. } /* shift>0 */
  3500. else { /* shift<0) .. RHS is to left of LHS; mirror shift>0 */
  3501. uc=bufr; /* RHS pointer */
  3502. /* pad bufr so right-aligned; most shifts will fit in 8 */
  3503. UBFROMUI(bufr+DECPMAX+QUAD*2, 0); /* add eight zeros */
  3504. UBFROMUI(bufr+DECPMAX+QUAD*2+4, 0); /* .. */
  3505. if (shift<-8) {
  3506. /* more than eight; fill the rest, and also worth doing the */
  3507. /* lead-in by fours */
  3508. uByte *up; /* work */
  3509. uByte *upend=bufr+DECPMAX+QUAD*2-shift;
  3510. for (up=bufr+DECPMAX+QUAD*2+8; up<upend; up+=4) UBFROMUI(up, 0);
  3511. /* [pads up to 36 in all for Quad] */
  3512. for (;; uc+=4) {
  3513. if (UBTOUI(uc)!=0) return sigr;
  3514. if (uc+4>bufr-shift-4) break;
  3515. }
  3516. }
  3517. /* check remaining leading digits */
  3518. for (; uc<bufr-shift; uc++) if (*uc!=0) return sigr;
  3519. /* now start the overlapped part; bufr has been padded, so the */
  3520. /* comparison can go for the full length of bufl, which is a */
  3521. /* multiple of 4 bytes */
  3522. for (ub=bufl; ; ub+=4, uc+=4) {
  3523. uInt ui=UBTOUI(ub);
  3524. if (ui!=UBTOUI(uc)) { /* mismatch found */
  3525. for (;; ub++, uc++) { /* check from left [little-endian?] */
  3526. if (*ub>*uc) return sigl; /* difference found */
  3527. if (*ub<*uc) return sigr; /* .. */
  3528. }
  3529. } /* mismatch */
  3530. if (ub==bufl+QUAD*2+DECPMAX-4) break; /* all checked */
  3531. }
  3532. } /* shift<0 */
  3533. /* Here when compare equal */
  3534. if (!tot) return 0; /* numerically equal */
  3535. /* total ordering .. exponent matters */
  3536. if (shift>0) return sigl; /* total order by exponent */
  3537. if (shift<0) return sigr; /* .. */
  3538. return 0;
  3539. } /* decNumCompare */
  3540. /* ------------------------------------------------------------------ */
  3541. /* decToInt32 -- local routine to effect ToInteger conversions */
  3542. /* */
  3543. /* df is the decFloat to convert */
  3544. /* set is the context */
  3545. /* rmode is the rounding mode to use */
  3546. /* exact is 1 if Inexact should be signalled */
  3547. /* unsign is 1 if the result a uInt, 0 if an Int (cast to uInt) */
  3548. /* returns 32-bit result as a uInt */
  3549. /* */
  3550. /* Invalid is set is df is a NaN, is infinite, or is out-of-range; in */
  3551. /* these cases 0 is returned. */
  3552. /* ------------------------------------------------------------------ */
  3553. static uInt decToInt32(const decFloat *df, decContext *set,
  3554. enum rounding rmode, Flag exact, Flag unsign) {
  3555. Int exp; /* exponent */
  3556. uInt sourhi, sourpen, sourlo; /* top word from source decFloat .. */
  3557. uInt hi, lo; /* .. penultimate, least, etc. */
  3558. decFloat zero, result; /* work */
  3559. Int i; /* .. */
  3560. /* Start decoding the argument */
  3561. sourhi=DFWORD(df, 0); /* top word */
  3562. exp=DECCOMBEXP[sourhi>>26]; /* get exponent high bits (in place) */
  3563. if (EXPISSPECIAL(exp)) { /* is special? */
  3564. set->status|=DEC_Invalid_operation; /* signal */
  3565. return 0;
  3566. }
  3567. /* Here when the argument is finite */
  3568. if (GETEXPUN(df)==0) result=*df; /* already a true integer */
  3569. else { /* need to round to integer */
  3570. enum rounding saveround; /* saver */
  3571. uInt savestatus; /* .. */
  3572. saveround=set->round; /* save rounding mode .. */
  3573. savestatus=set->status; /* .. and status */
  3574. set->round=rmode; /* set mode */
  3575. decFloatZero(&zero); /* make 0E+0 */
  3576. set->status=0; /* clear */
  3577. decFloatQuantize(&result, df, &zero, set); /* [this may fail] */
  3578. set->round=saveround; /* restore rounding mode .. */
  3579. if (exact) set->status|=savestatus; /* include Inexact */
  3580. else set->status=savestatus; /* .. or just original status */
  3581. }
  3582. /* only the last four declets of the coefficient can contain */
  3583. /* non-zero; check for others (and also NaN or Infinity from the */
  3584. /* Quantize) first (see DFISZERO for explanation): */
  3585. /* decFloatShow(&result, "sofar"); */
  3586. #if DOUBLE
  3587. if ((DFWORD(&result, 0)&0x1c03ff00)!=0
  3588. || (DFWORD(&result, 0)&0x60000000)==0x60000000) {
  3589. #elif QUAD
  3590. if ((DFWORD(&result, 2)&0xffffff00)!=0
  3591. || DFWORD(&result, 1)!=0
  3592. || (DFWORD(&result, 0)&0x1c003fff)!=0
  3593. || (DFWORD(&result, 0)&0x60000000)==0x60000000) {
  3594. #endif
  3595. set->status|=DEC_Invalid_operation; /* Invalid or out of range */
  3596. return 0;
  3597. }
  3598. /* get last twelve digits of the coefficent into hi & ho, base */
  3599. /* 10**9 (see GETCOEFFBILL): */
  3600. sourlo=DFWORD(&result, DECWORDS-1);
  3601. lo=DPD2BIN0[sourlo&0x3ff]
  3602. +DPD2BINK[(sourlo>>10)&0x3ff]
  3603. +DPD2BINM[(sourlo>>20)&0x3ff];
  3604. sourpen=DFWORD(&result, DECWORDS-2);
  3605. hi=DPD2BIN0[((sourpen<<2) | (sourlo>>30))&0x3ff];
  3606. /* according to request, check range carefully */
  3607. if (unsign) {
  3608. if (hi>4 || (hi==4 && lo>294967295) || (hi+lo!=0 && DFISSIGNED(&result))) {
  3609. set->status|=DEC_Invalid_operation; /* out of range */
  3610. return 0;
  3611. }
  3612. return hi*BILLION+lo;
  3613. }
  3614. /* signed */
  3615. if (hi>2 || (hi==2 && lo>147483647)) {
  3616. /* handle the usual edge case */
  3617. if (lo==147483648 && hi==2 && DFISSIGNED(&result)) return 0x80000000;
  3618. set->status|=DEC_Invalid_operation; /* truly out of range */
  3619. return 0;
  3620. }
  3621. i=hi*BILLION+lo;
  3622. if (DFISSIGNED(&result)) i=-i;
  3623. return (uInt)i;
  3624. } /* decToInt32 */
  3625. /* ------------------------------------------------------------------ */
  3626. /* decToIntegral -- local routine to effect ToIntegral value */
  3627. /* */
  3628. /* result gets the result */
  3629. /* df is the decFloat to round */
  3630. /* set is the context */
  3631. /* rmode is the rounding mode to use */
  3632. /* exact is 1 if Inexact should be signalled */
  3633. /* returns result */
  3634. /* ------------------------------------------------------------------ */
  3635. static decFloat * decToIntegral(decFloat *result, const decFloat *df,
  3636. decContext *set, enum rounding rmode,
  3637. Flag exact) {
  3638. Int exp; /* exponent */
  3639. uInt sourhi; /* top word from source decFloat */
  3640. enum rounding saveround; /* saver */
  3641. uInt savestatus; /* .. */
  3642. decFloat zero; /* work */
  3643. /* Start decoding the argument */
  3644. sourhi=DFWORD(df, 0); /* top word */
  3645. exp=DECCOMBEXP[sourhi>>26]; /* get exponent high bits (in place) */
  3646. if (EXPISSPECIAL(exp)) { /* is special? */
  3647. /* NaNs are handled as usual */
  3648. if (DFISNAN(df)) return decNaNs(result, df, NULL, set);
  3649. /* must be infinite; return canonical infinity with sign of df */
  3650. return decInfinity(result, df);
  3651. }
  3652. /* Here when the argument is finite */
  3653. /* complete extraction of the exponent */
  3654. exp+=GETECON(df)-DECBIAS; /* .. + continuation and unbias */
  3655. if (exp>=0) return decCanonical(result, df); /* already integral */
  3656. saveround=set->round; /* save rounding mode .. */
  3657. savestatus=set->status; /* .. and status */
  3658. set->round=rmode; /* set mode */
  3659. decFloatZero(&zero); /* make 0E+0 */
  3660. decFloatQuantize(result, df, &zero, set); /* 'integrate'; cannot fail */
  3661. set->round=saveround; /* restore rounding mode .. */
  3662. if (!exact) set->status=savestatus; /* .. and status, unless exact */
  3663. return result;
  3664. } /* decToIntegral */