APFloat.cpp 143 KB

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