APInt.cpp 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890
  1. //===-- APInt.cpp - Implement APInt 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 integer
  11. // constant values and provide a variety of arithmetic operations on them.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #define DEBUG_TYPE "apint"
  15. #include "llvm/ADT/APInt.h"
  16. #include "llvm/ADT/FoldingSet.h"
  17. #include "llvm/ADT/Hashing.h"
  18. #include "llvm/ADT/SmallString.h"
  19. #include "llvm/ADT/StringRef.h"
  20. #include "llvm/Support/Debug.h"
  21. #include "llvm/Support/ErrorHandling.h"
  22. #include "llvm/Support/MathExtras.h"
  23. #include "llvm/Support/raw_ostream.h"
  24. #include <cmath>
  25. #include <cstdlib>
  26. #include <cstring>
  27. #include <limits>
  28. using namespace llvm;
  29. /// A utility function for allocating memory, checking for allocation failures,
  30. /// and ensuring the contents are zeroed.
  31. inline static uint64_t* getClearedMemory(unsigned numWords) {
  32. uint64_t * result = new uint64_t[numWords];
  33. assert(result && "APInt memory allocation fails!");
  34. memset(result, 0, numWords * sizeof(uint64_t));
  35. return result;
  36. }
  37. /// A utility function for allocating memory and checking for allocation
  38. /// failure. The content is not zeroed.
  39. inline static uint64_t* getMemory(unsigned numWords) {
  40. uint64_t * result = new uint64_t[numWords];
  41. assert(result && "APInt memory allocation fails!");
  42. return result;
  43. }
  44. /// A utility function that converts a character to a digit.
  45. inline static unsigned getDigit(char cdigit, uint8_t radix) {
  46. unsigned r;
  47. if (radix == 16 || radix == 36) {
  48. r = cdigit - '0';
  49. if (r <= 9)
  50. return r;
  51. r = cdigit - 'A';
  52. if (r <= radix - 11U)
  53. return r + 10;
  54. r = cdigit - 'a';
  55. if (r <= radix - 11U)
  56. return r + 10;
  57. radix = 10;
  58. }
  59. r = cdigit - '0';
  60. if (r < radix)
  61. return r;
  62. return -1U;
  63. }
  64. void APInt::initSlowCase(unsigned numBits, uint64_t val, bool isSigned) {
  65. pVal = getClearedMemory(getNumWords());
  66. pVal[0] = val;
  67. if (isSigned && int64_t(val) < 0)
  68. for (unsigned i = 1; i < getNumWords(); ++i)
  69. pVal[i] = -1ULL;
  70. }
  71. void APInt::initSlowCase(const APInt& that) {
  72. pVal = getMemory(getNumWords());
  73. memcpy(pVal, that.pVal, getNumWords() * APINT_WORD_SIZE);
  74. }
  75. void APInt::initFromArray(ArrayRef<uint64_t> bigVal) {
  76. assert(BitWidth && "Bitwidth too small");
  77. assert(bigVal.data() && "Null pointer detected!");
  78. if (isSingleWord())
  79. VAL = bigVal[0];
  80. else {
  81. // Get memory, cleared to 0
  82. pVal = getClearedMemory(getNumWords());
  83. // Calculate the number of words to copy
  84. unsigned words = std::min<unsigned>(bigVal.size(), getNumWords());
  85. // Copy the words from bigVal to pVal
  86. memcpy(pVal, bigVal.data(), words * APINT_WORD_SIZE);
  87. }
  88. // Make sure unused high bits are cleared
  89. clearUnusedBits();
  90. }
  91. APInt::APInt(unsigned numBits, ArrayRef<uint64_t> bigVal)
  92. : BitWidth(numBits), VAL(0) {
  93. initFromArray(bigVal);
  94. }
  95. APInt::APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[])
  96. : BitWidth(numBits), VAL(0) {
  97. initFromArray(makeArrayRef(bigVal, numWords));
  98. }
  99. APInt::APInt(unsigned numbits, StringRef Str, uint8_t radix)
  100. : BitWidth(numbits), VAL(0) {
  101. assert(BitWidth && "Bitwidth too small");
  102. fromString(numbits, Str, radix);
  103. }
  104. APInt& APInt::AssignSlowCase(const APInt& RHS) {
  105. // Don't do anything for X = X
  106. if (this == &RHS)
  107. return *this;
  108. if (BitWidth == RHS.getBitWidth()) {
  109. // assume same bit-width single-word case is already handled
  110. assert(!isSingleWord());
  111. memcpy(pVal, RHS.pVal, getNumWords() * APINT_WORD_SIZE);
  112. return *this;
  113. }
  114. if (isSingleWord()) {
  115. // assume case where both are single words is already handled
  116. assert(!RHS.isSingleWord());
  117. VAL = 0;
  118. pVal = getMemory(RHS.getNumWords());
  119. memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
  120. } else if (getNumWords() == RHS.getNumWords())
  121. memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
  122. else if (RHS.isSingleWord()) {
  123. delete [] pVal;
  124. VAL = RHS.VAL;
  125. } else {
  126. delete [] pVal;
  127. pVal = getMemory(RHS.getNumWords());
  128. memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
  129. }
  130. BitWidth = RHS.BitWidth;
  131. return clearUnusedBits();
  132. }
  133. APInt& APInt::operator=(uint64_t RHS) {
  134. if (isSingleWord())
  135. VAL = RHS;
  136. else {
  137. pVal[0] = RHS;
  138. memset(pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
  139. }
  140. return clearUnusedBits();
  141. }
  142. /// Profile - This method 'profiles' an APInt for use with FoldingSet.
  143. void APInt::Profile(FoldingSetNodeID& ID) const {
  144. ID.AddInteger(BitWidth);
  145. if (isSingleWord()) {
  146. ID.AddInteger(VAL);
  147. return;
  148. }
  149. unsigned NumWords = getNumWords();
  150. for (unsigned i = 0; i < NumWords; ++i)
  151. ID.AddInteger(pVal[i]);
  152. }
  153. /// add_1 - This function adds a single "digit" integer, y, to the multiple
  154. /// "digit" integer array, x[]. x[] is modified to reflect the addition and
  155. /// 1 is returned if there is a carry out, otherwise 0 is returned.
  156. /// @returns the carry of the addition.
  157. static bool add_1(uint64_t dest[], uint64_t x[], unsigned len, uint64_t y) {
  158. for (unsigned i = 0; i < len; ++i) {
  159. dest[i] = y + x[i];
  160. if (dest[i] < y)
  161. y = 1; // Carry one to next digit.
  162. else {
  163. y = 0; // No need to carry so exit early
  164. break;
  165. }
  166. }
  167. return y;
  168. }
  169. /// @brief Prefix increment operator. Increments the APInt by one.
  170. APInt& APInt::operator++() {
  171. if (isSingleWord())
  172. ++VAL;
  173. else
  174. add_1(pVal, pVal, getNumWords(), 1);
  175. return clearUnusedBits();
  176. }
  177. /// sub_1 - This function subtracts a single "digit" (64-bit word), y, from
  178. /// the multi-digit integer array, x[], propagating the borrowed 1 value until
  179. /// no further borrowing is neeeded or it runs out of "digits" in x. The result
  180. /// is 1 if "borrowing" exhausted the digits in x, or 0 if x was not exhausted.
  181. /// In other words, if y > x then this function returns 1, otherwise 0.
  182. /// @returns the borrow out of the subtraction
  183. static bool sub_1(uint64_t x[], unsigned len, uint64_t y) {
  184. for (unsigned i = 0; i < len; ++i) {
  185. uint64_t X = x[i];
  186. x[i] -= y;
  187. if (y > X)
  188. y = 1; // We have to "borrow 1" from next "digit"
  189. else {
  190. y = 0; // No need to borrow
  191. break; // Remaining digits are unchanged so exit early
  192. }
  193. }
  194. return bool(y);
  195. }
  196. /// @brief Prefix decrement operator. Decrements the APInt by one.
  197. APInt& APInt::operator--() {
  198. if (isSingleWord())
  199. --VAL;
  200. else
  201. sub_1(pVal, getNumWords(), 1);
  202. return clearUnusedBits();
  203. }
  204. /// add - This function adds the integer array x to the integer array Y and
  205. /// places the result in dest.
  206. /// @returns the carry out from the addition
  207. /// @brief General addition of 64-bit integer arrays
  208. static bool add(uint64_t *dest, const uint64_t *x, const uint64_t *y,
  209. unsigned len) {
  210. bool carry = false;
  211. for (unsigned i = 0; i< len; ++i) {
  212. uint64_t limit = std::min(x[i],y[i]); // must come first in case dest == x
  213. dest[i] = x[i] + y[i] + carry;
  214. carry = dest[i] < limit || (carry && dest[i] == limit);
  215. }
  216. return carry;
  217. }
  218. /// Adds the RHS APint to this APInt.
  219. /// @returns this, after addition of RHS.
  220. /// @brief Addition assignment operator.
  221. APInt& APInt::operator+=(const APInt& RHS) {
  222. assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
  223. if (isSingleWord())
  224. VAL += RHS.VAL;
  225. else {
  226. add(pVal, pVal, RHS.pVal, getNumWords());
  227. }
  228. return clearUnusedBits();
  229. }
  230. /// Subtracts the integer array y from the integer array x
  231. /// @returns returns the borrow out.
  232. /// @brief Generalized subtraction of 64-bit integer arrays.
  233. static bool sub(uint64_t *dest, const uint64_t *x, const uint64_t *y,
  234. unsigned len) {
  235. bool borrow = false;
  236. for (unsigned i = 0; i < len; ++i) {
  237. uint64_t x_tmp = borrow ? x[i] - 1 : x[i];
  238. borrow = y[i] > x_tmp || (borrow && x[i] == 0);
  239. dest[i] = x_tmp - y[i];
  240. }
  241. return borrow;
  242. }
  243. /// Subtracts the RHS APInt from this APInt
  244. /// @returns this, after subtraction
  245. /// @brief Subtraction assignment operator.
  246. APInt& APInt::operator-=(const APInt& RHS) {
  247. assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
  248. if (isSingleWord())
  249. VAL -= RHS.VAL;
  250. else
  251. sub(pVal, pVal, RHS.pVal, getNumWords());
  252. return clearUnusedBits();
  253. }
  254. /// Multiplies an integer array, x, by a uint64_t integer and places the result
  255. /// into dest.
  256. /// @returns the carry out of the multiplication.
  257. /// @brief Multiply a multi-digit APInt by a single digit (64-bit) integer.
  258. static uint64_t mul_1(uint64_t dest[], uint64_t x[], unsigned len, uint64_t y) {
  259. // Split y into high 32-bit part (hy) and low 32-bit part (ly)
  260. uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
  261. uint64_t carry = 0;
  262. // For each digit of x.
  263. for (unsigned i = 0; i < len; ++i) {
  264. // Split x into high and low words
  265. uint64_t lx = x[i] & 0xffffffffULL;
  266. uint64_t hx = x[i] >> 32;
  267. // hasCarry - A flag to indicate if there is a carry to the next digit.
  268. // hasCarry == 0, no carry
  269. // hasCarry == 1, has carry
  270. // hasCarry == 2, no carry and the calculation result == 0.
  271. uint8_t hasCarry = 0;
  272. dest[i] = carry + lx * ly;
  273. // Determine if the add above introduces carry.
  274. hasCarry = (dest[i] < carry) ? 1 : 0;
  275. carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
  276. // The upper limit of carry can be (2^32 - 1)(2^32 - 1) +
  277. // (2^32 - 1) + 2^32 = 2^64.
  278. hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
  279. carry += (lx * hy) & 0xffffffffULL;
  280. dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
  281. carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) +
  282. (carry >> 32) + ((lx * hy) >> 32) + hx * hy;
  283. }
  284. return carry;
  285. }
  286. /// Multiplies integer array x by integer array y and stores the result into
  287. /// the integer array dest. Note that dest's size must be >= xlen + ylen.
  288. /// @brief Generalized multiplicate of integer arrays.
  289. static void mul(uint64_t dest[], uint64_t x[], unsigned xlen, uint64_t y[],
  290. unsigned ylen) {
  291. dest[xlen] = mul_1(dest, x, xlen, y[0]);
  292. for (unsigned i = 1; i < ylen; ++i) {
  293. uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
  294. uint64_t carry = 0, lx = 0, hx = 0;
  295. for (unsigned j = 0; j < xlen; ++j) {
  296. lx = x[j] & 0xffffffffULL;
  297. hx = x[j] >> 32;
  298. // hasCarry - A flag to indicate if has carry.
  299. // hasCarry == 0, no carry
  300. // hasCarry == 1, has carry
  301. // hasCarry == 2, no carry and the calculation result == 0.
  302. uint8_t hasCarry = 0;
  303. uint64_t resul = carry + lx * ly;
  304. hasCarry = (resul < carry) ? 1 : 0;
  305. carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
  306. hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
  307. carry += (lx * hy) & 0xffffffffULL;
  308. resul = (carry << 32) | (resul & 0xffffffffULL);
  309. dest[i+j] += resul;
  310. carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
  311. (carry >> 32) + (dest[i+j] < resul ? 1 : 0) +
  312. ((lx * hy) >> 32) + hx * hy;
  313. }
  314. dest[i+xlen] = carry;
  315. }
  316. }
  317. APInt& APInt::operator*=(const APInt& RHS) {
  318. assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
  319. if (isSingleWord()) {
  320. VAL *= RHS.VAL;
  321. clearUnusedBits();
  322. return *this;
  323. }
  324. // Get some bit facts about LHS and check for zero
  325. unsigned lhsBits = getActiveBits();
  326. unsigned lhsWords = !lhsBits ? 0 : whichWord(lhsBits - 1) + 1;
  327. if (!lhsWords)
  328. // 0 * X ===> 0
  329. return *this;
  330. // Get some bit facts about RHS and check for zero
  331. unsigned rhsBits = RHS.getActiveBits();
  332. unsigned rhsWords = !rhsBits ? 0 : whichWord(rhsBits - 1) + 1;
  333. if (!rhsWords) {
  334. // X * 0 ===> 0
  335. clearAllBits();
  336. return *this;
  337. }
  338. // Allocate space for the result
  339. unsigned destWords = rhsWords + lhsWords;
  340. uint64_t *dest = getMemory(destWords);
  341. // Perform the long multiply
  342. mul(dest, pVal, lhsWords, RHS.pVal, rhsWords);
  343. // Copy result back into *this
  344. clearAllBits();
  345. unsigned wordsToCopy = destWords >= getNumWords() ? getNumWords() : destWords;
  346. memcpy(pVal, dest, wordsToCopy * APINT_WORD_SIZE);
  347. clearUnusedBits();
  348. // delete dest array and return
  349. delete[] dest;
  350. return *this;
  351. }
  352. APInt& APInt::operator&=(const APInt& RHS) {
  353. assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
  354. if (isSingleWord()) {
  355. VAL &= RHS.VAL;
  356. return *this;
  357. }
  358. unsigned numWords = getNumWords();
  359. for (unsigned i = 0; i < numWords; ++i)
  360. pVal[i] &= RHS.pVal[i];
  361. return *this;
  362. }
  363. APInt& APInt::operator|=(const APInt& RHS) {
  364. assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
  365. if (isSingleWord()) {
  366. VAL |= RHS.VAL;
  367. return *this;
  368. }
  369. unsigned numWords = getNumWords();
  370. for (unsigned i = 0; i < numWords; ++i)
  371. pVal[i] |= RHS.pVal[i];
  372. return *this;
  373. }
  374. APInt& APInt::operator^=(const APInt& RHS) {
  375. assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
  376. if (isSingleWord()) {
  377. VAL ^= RHS.VAL;
  378. this->clearUnusedBits();
  379. return *this;
  380. }
  381. unsigned numWords = getNumWords();
  382. for (unsigned i = 0; i < numWords; ++i)
  383. pVal[i] ^= RHS.pVal[i];
  384. return clearUnusedBits();
  385. }
  386. APInt APInt::AndSlowCase(const APInt& RHS) const {
  387. unsigned numWords = getNumWords();
  388. uint64_t* val = getMemory(numWords);
  389. for (unsigned i = 0; i < numWords; ++i)
  390. val[i] = pVal[i] & RHS.pVal[i];
  391. return APInt(val, getBitWidth());
  392. }
  393. APInt APInt::OrSlowCase(const APInt& RHS) const {
  394. unsigned numWords = getNumWords();
  395. uint64_t *val = getMemory(numWords);
  396. for (unsigned i = 0; i < numWords; ++i)
  397. val[i] = pVal[i] | RHS.pVal[i];
  398. return APInt(val, getBitWidth());
  399. }
  400. APInt APInt::XorSlowCase(const APInt& RHS) const {
  401. unsigned numWords = getNumWords();
  402. uint64_t *val = getMemory(numWords);
  403. for (unsigned i = 0; i < numWords; ++i)
  404. val[i] = pVal[i] ^ RHS.pVal[i];
  405. // 0^0==1 so clear the high bits in case they got set.
  406. return APInt(val, getBitWidth()).clearUnusedBits();
  407. }
  408. APInt APInt::operator*(const APInt& RHS) const {
  409. assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
  410. if (isSingleWord())
  411. return APInt(BitWidth, VAL * RHS.VAL);
  412. APInt Result(*this);
  413. Result *= RHS;
  414. return Result;
  415. }
  416. APInt APInt::operator+(const APInt& RHS) const {
  417. assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
  418. if (isSingleWord())
  419. return APInt(BitWidth, VAL + RHS.VAL);
  420. APInt Result(BitWidth, 0);
  421. add(Result.pVal, this->pVal, RHS.pVal, getNumWords());
  422. return Result.clearUnusedBits();
  423. }
  424. APInt APInt::operator-(const APInt& RHS) const {
  425. assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
  426. if (isSingleWord())
  427. return APInt(BitWidth, VAL - RHS.VAL);
  428. APInt Result(BitWidth, 0);
  429. sub(Result.pVal, this->pVal, RHS.pVal, getNumWords());
  430. return Result.clearUnusedBits();
  431. }
  432. bool APInt::EqualSlowCase(const APInt& RHS) const {
  433. // Get some facts about the number of bits used in the two operands.
  434. unsigned n1 = getActiveBits();
  435. unsigned n2 = RHS.getActiveBits();
  436. // If the number of bits isn't the same, they aren't equal
  437. if (n1 != n2)
  438. return false;
  439. // If the number of bits fits in a word, we only need to compare the low word.
  440. if (n1 <= APINT_BITS_PER_WORD)
  441. return pVal[0] == RHS.pVal[0];
  442. // Otherwise, compare everything
  443. for (int i = whichWord(n1 - 1); i >= 0; --i)
  444. if (pVal[i] != RHS.pVal[i])
  445. return false;
  446. return true;
  447. }
  448. bool APInt::EqualSlowCase(uint64_t Val) const {
  449. unsigned n = getActiveBits();
  450. if (n <= APINT_BITS_PER_WORD)
  451. return pVal[0] == Val;
  452. else
  453. return false;
  454. }
  455. bool APInt::ult(const APInt& RHS) const {
  456. assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
  457. if (isSingleWord())
  458. return VAL < RHS.VAL;
  459. // Get active bit length of both operands
  460. unsigned n1 = getActiveBits();
  461. unsigned n2 = RHS.getActiveBits();
  462. // If magnitude of LHS is less than RHS, return true.
  463. if (n1 < n2)
  464. return true;
  465. // If magnitude of RHS is greather than LHS, return false.
  466. if (n2 < n1)
  467. return false;
  468. // If they bot fit in a word, just compare the low order word
  469. if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
  470. return pVal[0] < RHS.pVal[0];
  471. // Otherwise, compare all words
  472. unsigned topWord = whichWord(std::max(n1,n2)-1);
  473. for (int i = topWord; i >= 0; --i) {
  474. if (pVal[i] > RHS.pVal[i])
  475. return false;
  476. if (pVal[i] < RHS.pVal[i])
  477. return true;
  478. }
  479. return false;
  480. }
  481. bool APInt::slt(const APInt& RHS) const {
  482. assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
  483. if (isSingleWord()) {
  484. int64_t lhsSext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
  485. int64_t rhsSext = (int64_t(RHS.VAL) << (64-BitWidth)) >> (64-BitWidth);
  486. return lhsSext < rhsSext;
  487. }
  488. APInt lhs(*this);
  489. APInt rhs(RHS);
  490. bool lhsNeg = isNegative();
  491. bool rhsNeg = rhs.isNegative();
  492. if (lhsNeg) {
  493. // Sign bit is set so perform two's complement to make it positive
  494. lhs.flipAllBits();
  495. ++lhs;
  496. }
  497. if (rhsNeg) {
  498. // Sign bit is set so perform two's complement to make it positive
  499. rhs.flipAllBits();
  500. ++rhs;
  501. }
  502. // Now we have unsigned values to compare so do the comparison if necessary
  503. // based on the negativeness of the values.
  504. if (lhsNeg)
  505. if (rhsNeg)
  506. return lhs.ugt(rhs);
  507. else
  508. return true;
  509. else if (rhsNeg)
  510. return false;
  511. else
  512. return lhs.ult(rhs);
  513. }
  514. void APInt::setBit(unsigned bitPosition) {
  515. if (isSingleWord())
  516. VAL |= maskBit(bitPosition);
  517. else
  518. pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
  519. }
  520. /// Set the given bit to 0 whose position is given as "bitPosition".
  521. /// @brief Set a given bit to 0.
  522. void APInt::clearBit(unsigned bitPosition) {
  523. if (isSingleWord())
  524. VAL &= ~maskBit(bitPosition);
  525. else
  526. pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
  527. }
  528. /// @brief Toggle every bit to its opposite value.
  529. /// Toggle a given bit to its opposite value whose position is given
  530. /// as "bitPosition".
  531. /// @brief Toggles a given bit to its opposite value.
  532. void APInt::flipBit(unsigned bitPosition) {
  533. assert(bitPosition < BitWidth && "Out of the bit-width range!");
  534. if ((*this)[bitPosition]) clearBit(bitPosition);
  535. else setBit(bitPosition);
  536. }
  537. unsigned APInt::getBitsNeeded(StringRef str, uint8_t radix) {
  538. assert(!str.empty() && "Invalid string length");
  539. assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 ||
  540. radix == 36) &&
  541. "Radix should be 2, 8, 10, 16, or 36!");
  542. size_t slen = str.size();
  543. // Each computation below needs to know if it's negative.
  544. StringRef::iterator p = str.begin();
  545. unsigned isNegative = *p == '-';
  546. if (*p == '-' || *p == '+') {
  547. p++;
  548. slen--;
  549. assert(slen && "String is only a sign, needs a value.");
  550. }
  551. // For radixes of power-of-two values, the bits required is accurately and
  552. // easily computed
  553. if (radix == 2)
  554. return slen + isNegative;
  555. if (radix == 8)
  556. return slen * 3 + isNegative;
  557. if (radix == 16)
  558. return slen * 4 + isNegative;
  559. // FIXME: base 36
  560. // This is grossly inefficient but accurate. We could probably do something
  561. // with a computation of roughly slen*64/20 and then adjust by the value of
  562. // the first few digits. But, I'm not sure how accurate that could be.
  563. // Compute a sufficient number of bits that is always large enough but might
  564. // be too large. This avoids the assertion in the constructor. This
  565. // calculation doesn't work appropriately for the numbers 0-9, so just use 4
  566. // bits in that case.
  567. unsigned sufficient
  568. = radix == 10? (slen == 1 ? 4 : slen * 64/18)
  569. : (slen == 1 ? 7 : slen * 16/3);
  570. // Convert to the actual binary value.
  571. APInt tmp(sufficient, StringRef(p, slen), radix);
  572. // Compute how many bits are required. If the log is infinite, assume we need
  573. // just bit.
  574. unsigned log = tmp.logBase2();
  575. if (log == (unsigned)-1) {
  576. return isNegative + 1;
  577. } else {
  578. return isNegative + log + 1;
  579. }
  580. }
  581. hash_code llvm::hash_value(const APInt &Arg) {
  582. if (Arg.isSingleWord())
  583. return hash_combine(Arg.VAL);
  584. return hash_combine_range(Arg.pVal, Arg.pVal + Arg.getNumWords());
  585. }
  586. /// HiBits - This function returns the high "numBits" bits of this APInt.
  587. APInt APInt::getHiBits(unsigned numBits) const {
  588. return APIntOps::lshr(*this, BitWidth - numBits);
  589. }
  590. /// LoBits - This function returns the low "numBits" bits of this APInt.
  591. APInt APInt::getLoBits(unsigned numBits) const {
  592. return APIntOps::lshr(APIntOps::shl(*this, BitWidth - numBits),
  593. BitWidth - numBits);
  594. }
  595. unsigned APInt::countLeadingZerosSlowCase() const {
  596. // Treat the most significand word differently because it might have
  597. // meaningless bits set beyond the precision.
  598. unsigned BitsInMSW = BitWidth % APINT_BITS_PER_WORD;
  599. integerPart MSWMask;
  600. if (BitsInMSW) MSWMask = (integerPart(1) << BitsInMSW) - 1;
  601. else {
  602. MSWMask = ~integerPart(0);
  603. BitsInMSW = APINT_BITS_PER_WORD;
  604. }
  605. unsigned i = getNumWords();
  606. integerPart MSW = pVal[i-1] & MSWMask;
  607. if (MSW)
  608. return llvm::countLeadingZeros(MSW) - (APINT_BITS_PER_WORD - BitsInMSW);
  609. unsigned Count = BitsInMSW;
  610. for (--i; i > 0u; --i) {
  611. if (pVal[i-1] == 0)
  612. Count += APINT_BITS_PER_WORD;
  613. else {
  614. Count += llvm::countLeadingZeros(pVal[i-1]);
  615. break;
  616. }
  617. }
  618. return Count;
  619. }
  620. unsigned APInt::countLeadingOnes() const {
  621. if (isSingleWord())
  622. return CountLeadingOnes_64(VAL << (APINT_BITS_PER_WORD - BitWidth));
  623. unsigned highWordBits = BitWidth % APINT_BITS_PER_WORD;
  624. unsigned shift;
  625. if (!highWordBits) {
  626. highWordBits = APINT_BITS_PER_WORD;
  627. shift = 0;
  628. } else {
  629. shift = APINT_BITS_PER_WORD - highWordBits;
  630. }
  631. int i = getNumWords() - 1;
  632. unsigned Count = CountLeadingOnes_64(pVal[i] << shift);
  633. if (Count == highWordBits) {
  634. for (i--; i >= 0; --i) {
  635. if (pVal[i] == -1ULL)
  636. Count += APINT_BITS_PER_WORD;
  637. else {
  638. Count += CountLeadingOnes_64(pVal[i]);
  639. break;
  640. }
  641. }
  642. }
  643. return Count;
  644. }
  645. unsigned APInt::countTrailingZeros() const {
  646. if (isSingleWord())
  647. return std::min(unsigned(llvm::countTrailingZeros(VAL)), BitWidth);
  648. unsigned Count = 0;
  649. unsigned i = 0;
  650. for (; i < getNumWords() && pVal[i] == 0; ++i)
  651. Count += APINT_BITS_PER_WORD;
  652. if (i < getNumWords())
  653. Count += llvm::countTrailingZeros(pVal[i]);
  654. return std::min(Count, BitWidth);
  655. }
  656. unsigned APInt::countTrailingOnesSlowCase() const {
  657. unsigned Count = 0;
  658. unsigned i = 0;
  659. for (; i < getNumWords() && pVal[i] == -1ULL; ++i)
  660. Count += APINT_BITS_PER_WORD;
  661. if (i < getNumWords())
  662. Count += CountTrailingOnes_64(pVal[i]);
  663. return std::min(Count, BitWidth);
  664. }
  665. unsigned APInt::countPopulationSlowCase() const {
  666. unsigned Count = 0;
  667. for (unsigned i = 0; i < getNumWords(); ++i)
  668. Count += CountPopulation_64(pVal[i]);
  669. return Count;
  670. }
  671. /// Perform a logical right-shift from Src to Dst, which must be equal or
  672. /// non-overlapping, of Words words, by Shift, which must be less than 64.
  673. static void lshrNear(uint64_t *Dst, uint64_t *Src, unsigned Words,
  674. unsigned Shift) {
  675. uint64_t Carry = 0;
  676. for (int I = Words - 1; I >= 0; --I) {
  677. uint64_t Tmp = Src[I];
  678. Dst[I] = (Tmp >> Shift) | Carry;
  679. Carry = Tmp << (64 - Shift);
  680. }
  681. }
  682. APInt APInt::byteSwap() const {
  683. assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
  684. if (BitWidth == 16)
  685. return APInt(BitWidth, ByteSwap_16(uint16_t(VAL)));
  686. if (BitWidth == 32)
  687. return APInt(BitWidth, ByteSwap_32(unsigned(VAL)));
  688. if (BitWidth == 48) {
  689. unsigned Tmp1 = unsigned(VAL >> 16);
  690. Tmp1 = ByteSwap_32(Tmp1);
  691. uint16_t Tmp2 = uint16_t(VAL);
  692. Tmp2 = ByteSwap_16(Tmp2);
  693. return APInt(BitWidth, (uint64_t(Tmp2) << 32) | Tmp1);
  694. }
  695. if (BitWidth == 64)
  696. return APInt(BitWidth, ByteSwap_64(VAL));
  697. APInt Result(getNumWords() * APINT_BITS_PER_WORD, 0);
  698. for (unsigned I = 0, N = getNumWords(); I != N; ++I)
  699. Result.pVal[I] = ByteSwap_64(pVal[N - I - 1]);
  700. if (Result.BitWidth != BitWidth) {
  701. lshrNear(Result.pVal, Result.pVal, getNumWords(),
  702. Result.BitWidth - BitWidth);
  703. Result.BitWidth = BitWidth;
  704. }
  705. return Result;
  706. }
  707. APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1,
  708. const APInt& API2) {
  709. APInt A = API1, B = API2;
  710. while (!!B) {
  711. APInt T = B;
  712. B = APIntOps::urem(A, B);
  713. A = T;
  714. }
  715. return A;
  716. }
  717. APInt llvm::APIntOps::RoundDoubleToAPInt(double Double, unsigned width) {
  718. union {
  719. double D;
  720. uint64_t I;
  721. } T;
  722. T.D = Double;
  723. // Get the sign bit from the highest order bit
  724. bool isNeg = T.I >> 63;
  725. // Get the 11-bit exponent and adjust for the 1023 bit bias
  726. int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
  727. // If the exponent is negative, the value is < 0 so just return 0.
  728. if (exp < 0)
  729. return APInt(width, 0u);
  730. // Extract the mantissa by clearing the top 12 bits (sign + exponent).
  731. uint64_t mantissa = (T.I & (~0ULL >> 12)) | 1ULL << 52;
  732. // If the exponent doesn't shift all bits out of the mantissa
  733. if (exp < 52)
  734. return isNeg ? -APInt(width, mantissa >> (52 - exp)) :
  735. APInt(width, mantissa >> (52 - exp));
  736. // If the client didn't provide enough bits for us to shift the mantissa into
  737. // then the result is undefined, just return 0
  738. if (width <= exp - 52)
  739. return APInt(width, 0);
  740. // Otherwise, we have to shift the mantissa bits up to the right location
  741. APInt Tmp(width, mantissa);
  742. Tmp = Tmp.shl((unsigned)exp - 52);
  743. return isNeg ? -Tmp : Tmp;
  744. }
  745. /// RoundToDouble - This function converts this APInt to a double.
  746. /// The layout for double is as following (IEEE Standard 754):
  747. /// --------------------------------------
  748. /// | Sign Exponent Fraction Bias |
  749. /// |-------------------------------------- |
  750. /// | 1[63] 11[62-52] 52[51-00] 1023 |
  751. /// --------------------------------------
  752. double APInt::roundToDouble(bool isSigned) const {
  753. // Handle the simple case where the value is contained in one uint64_t.
  754. // It is wrong to optimize getWord(0) to VAL; there might be more than one word.
  755. if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
  756. if (isSigned) {
  757. int64_t sext = (int64_t(getWord(0)) << (64-BitWidth)) >> (64-BitWidth);
  758. return double(sext);
  759. } else
  760. return double(getWord(0));
  761. }
  762. // Determine if the value is negative.
  763. bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
  764. // Construct the absolute value if we're negative.
  765. APInt Tmp(isNeg ? -(*this) : (*this));
  766. // Figure out how many bits we're using.
  767. unsigned n = Tmp.getActiveBits();
  768. // The exponent (without bias normalization) is just the number of bits
  769. // we are using. Note that the sign bit is gone since we constructed the
  770. // absolute value.
  771. uint64_t exp = n;
  772. // Return infinity for exponent overflow
  773. if (exp > 1023) {
  774. if (!isSigned || !isNeg)
  775. return std::numeric_limits<double>::infinity();
  776. else
  777. return -std::numeric_limits<double>::infinity();
  778. }
  779. exp += 1023; // Increment for 1023 bias
  780. // Number of bits in mantissa is 52. To obtain the mantissa value, we must
  781. // extract the high 52 bits from the correct words in pVal.
  782. uint64_t mantissa;
  783. unsigned hiWord = whichWord(n-1);
  784. if (hiWord == 0) {
  785. mantissa = Tmp.pVal[0];
  786. if (n > 52)
  787. mantissa >>= n - 52; // shift down, we want the top 52 bits.
  788. } else {
  789. assert(hiWord > 0 && "huh?");
  790. uint64_t hibits = Tmp.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
  791. uint64_t lobits = Tmp.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
  792. mantissa = hibits | lobits;
  793. }
  794. // The leading bit of mantissa is implicit, so get rid of it.
  795. uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
  796. union {
  797. double D;
  798. uint64_t I;
  799. } T;
  800. T.I = sign | (exp << 52) | mantissa;
  801. return T.D;
  802. }
  803. // Truncate to new width.
  804. APInt APInt::trunc(unsigned width) const {
  805. assert(width < BitWidth && "Invalid APInt Truncate request");
  806. assert(width && "Can't truncate to 0 bits");
  807. if (width <= APINT_BITS_PER_WORD)
  808. return APInt(width, getRawData()[0]);
  809. APInt Result(getMemory(getNumWords(width)), width);
  810. // Copy full words.
  811. unsigned i;
  812. for (i = 0; i != width / APINT_BITS_PER_WORD; i++)
  813. Result.pVal[i] = pVal[i];
  814. // Truncate and copy any partial word.
  815. unsigned bits = (0 - width) % APINT_BITS_PER_WORD;
  816. if (bits != 0)
  817. Result.pVal[i] = pVal[i] << bits >> bits;
  818. return Result;
  819. }
  820. // Sign extend to a new width.
  821. APInt APInt::sext(unsigned width) const {
  822. assert(width > BitWidth && "Invalid APInt SignExtend request");
  823. if (width <= APINT_BITS_PER_WORD) {
  824. uint64_t val = VAL << (APINT_BITS_PER_WORD - BitWidth);
  825. val = (int64_t)val >> (width - BitWidth);
  826. return APInt(width, val >> (APINT_BITS_PER_WORD - width));
  827. }
  828. APInt Result(getMemory(getNumWords(width)), width);
  829. // Copy full words.
  830. unsigned i;
  831. uint64_t word = 0;
  832. for (i = 0; i != BitWidth / APINT_BITS_PER_WORD; i++) {
  833. word = getRawData()[i];
  834. Result.pVal[i] = word;
  835. }
  836. // Read and sign-extend any partial word.
  837. unsigned bits = (0 - BitWidth) % APINT_BITS_PER_WORD;
  838. if (bits != 0)
  839. word = (int64_t)getRawData()[i] << bits >> bits;
  840. else
  841. word = (int64_t)word >> (APINT_BITS_PER_WORD - 1);
  842. // Write remaining full words.
  843. for (; i != width / APINT_BITS_PER_WORD; i++) {
  844. Result.pVal[i] = word;
  845. word = (int64_t)word >> (APINT_BITS_PER_WORD - 1);
  846. }
  847. // Write any partial word.
  848. bits = (0 - width) % APINT_BITS_PER_WORD;
  849. if (bits != 0)
  850. Result.pVal[i] = word << bits >> bits;
  851. return Result;
  852. }
  853. // Zero extend to a new width.
  854. APInt APInt::zext(unsigned width) const {
  855. assert(width > BitWidth && "Invalid APInt ZeroExtend request");
  856. if (width <= APINT_BITS_PER_WORD)
  857. return APInt(width, VAL);
  858. APInt Result(getMemory(getNumWords(width)), width);
  859. // Copy words.
  860. unsigned i;
  861. for (i = 0; i != getNumWords(); i++)
  862. Result.pVal[i] = getRawData()[i];
  863. // Zero remaining words.
  864. memset(&Result.pVal[i], 0, (Result.getNumWords() - i) * APINT_WORD_SIZE);
  865. return Result;
  866. }
  867. APInt APInt::zextOrTrunc(unsigned width) const {
  868. if (BitWidth < width)
  869. return zext(width);
  870. if (BitWidth > width)
  871. return trunc(width);
  872. return *this;
  873. }
  874. APInt APInt::sextOrTrunc(unsigned width) const {
  875. if (BitWidth < width)
  876. return sext(width);
  877. if (BitWidth > width)
  878. return trunc(width);
  879. return *this;
  880. }
  881. APInt APInt::zextOrSelf(unsigned width) const {
  882. if (BitWidth < width)
  883. return zext(width);
  884. return *this;
  885. }
  886. APInt APInt::sextOrSelf(unsigned width) const {
  887. if (BitWidth < width)
  888. return sext(width);
  889. return *this;
  890. }
  891. /// Arithmetic right-shift this APInt by shiftAmt.
  892. /// @brief Arithmetic right-shift function.
  893. APInt APInt::ashr(const APInt &shiftAmt) const {
  894. return ashr((unsigned)shiftAmt.getLimitedValue(BitWidth));
  895. }
  896. /// Arithmetic right-shift this APInt by shiftAmt.
  897. /// @brief Arithmetic right-shift function.
  898. APInt APInt::ashr(unsigned shiftAmt) const {
  899. assert(shiftAmt <= BitWidth && "Invalid shift amount");
  900. // Handle a degenerate case
  901. if (shiftAmt == 0)
  902. return *this;
  903. // Handle single word shifts with built-in ashr
  904. if (isSingleWord()) {
  905. if (shiftAmt == BitWidth)
  906. return APInt(BitWidth, 0); // undefined
  907. else {
  908. unsigned SignBit = APINT_BITS_PER_WORD - BitWidth;
  909. return APInt(BitWidth,
  910. (((int64_t(VAL) << SignBit) >> SignBit) >> shiftAmt));
  911. }
  912. }
  913. // If all the bits were shifted out, the result is, technically, undefined.
  914. // We return -1 if it was negative, 0 otherwise. We check this early to avoid
  915. // issues in the algorithm below.
  916. if (shiftAmt == BitWidth) {
  917. if (isNegative())
  918. return APInt(BitWidth, -1ULL, true);
  919. else
  920. return APInt(BitWidth, 0);
  921. }
  922. // Create some space for the result.
  923. uint64_t * val = new uint64_t[getNumWords()];
  924. // Compute some values needed by the following shift algorithms
  925. unsigned wordShift = shiftAmt % APINT_BITS_PER_WORD; // bits to shift per word
  926. unsigned offset = shiftAmt / APINT_BITS_PER_WORD; // word offset for shift
  927. unsigned breakWord = getNumWords() - 1 - offset; // last word affected
  928. unsigned bitsInWord = whichBit(BitWidth); // how many bits in last word?
  929. if (bitsInWord == 0)
  930. bitsInWord = APINT_BITS_PER_WORD;
  931. // If we are shifting whole words, just move whole words
  932. if (wordShift == 0) {
  933. // Move the words containing significant bits
  934. for (unsigned i = 0; i <= breakWord; ++i)
  935. val[i] = pVal[i+offset]; // move whole word
  936. // Adjust the top significant word for sign bit fill, if negative
  937. if (isNegative())
  938. if (bitsInWord < APINT_BITS_PER_WORD)
  939. val[breakWord] |= ~0ULL << bitsInWord; // set high bits
  940. } else {
  941. // Shift the low order words
  942. for (unsigned i = 0; i < breakWord; ++i) {
  943. // This combines the shifted corresponding word with the low bits from
  944. // the next word (shifted into this word's high bits).
  945. val[i] = (pVal[i+offset] >> wordShift) |
  946. (pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift));
  947. }
  948. // Shift the break word. In this case there are no bits from the next word
  949. // to include in this word.
  950. val[breakWord] = pVal[breakWord+offset] >> wordShift;
  951. // Deal with sign extension in the break word, and possibly the word before
  952. // it.
  953. if (isNegative()) {
  954. if (wordShift > bitsInWord) {
  955. if (breakWord > 0)
  956. val[breakWord-1] |=
  957. ~0ULL << (APINT_BITS_PER_WORD - (wordShift - bitsInWord));
  958. val[breakWord] |= ~0ULL;
  959. } else
  960. val[breakWord] |= (~0ULL << (bitsInWord - wordShift));
  961. }
  962. }
  963. // Remaining words are 0 or -1, just assign them.
  964. uint64_t fillValue = (isNegative() ? -1ULL : 0);
  965. for (unsigned i = breakWord+1; i < getNumWords(); ++i)
  966. val[i] = fillValue;
  967. return APInt(val, BitWidth).clearUnusedBits();
  968. }
  969. /// Logical right-shift this APInt by shiftAmt.
  970. /// @brief Logical right-shift function.
  971. APInt APInt::lshr(const APInt &shiftAmt) const {
  972. return lshr((unsigned)shiftAmt.getLimitedValue(BitWidth));
  973. }
  974. /// Logical right-shift this APInt by shiftAmt.
  975. /// @brief Logical right-shift function.
  976. APInt APInt::lshr(unsigned shiftAmt) const {
  977. if (isSingleWord()) {
  978. if (shiftAmt >= BitWidth)
  979. return APInt(BitWidth, 0);
  980. else
  981. return APInt(BitWidth, this->VAL >> shiftAmt);
  982. }
  983. // If all the bits were shifted out, the result is 0. This avoids issues
  984. // with shifting by the size of the integer type, which produces undefined
  985. // results. We define these "undefined results" to always be 0.
  986. if (shiftAmt >= BitWidth)
  987. return APInt(BitWidth, 0);
  988. // If none of the bits are shifted out, the result is *this. This avoids
  989. // issues with shifting by the size of the integer type, which produces
  990. // undefined results in the code below. This is also an optimization.
  991. if (shiftAmt == 0)
  992. return *this;
  993. // Create some space for the result.
  994. uint64_t * val = new uint64_t[getNumWords()];
  995. // If we are shifting less than a word, compute the shift with a simple carry
  996. if (shiftAmt < APINT_BITS_PER_WORD) {
  997. lshrNear(val, pVal, getNumWords(), shiftAmt);
  998. return APInt(val, BitWidth).clearUnusedBits();
  999. }
  1000. // Compute some values needed by the remaining shift algorithms
  1001. unsigned wordShift = shiftAmt % APINT_BITS_PER_WORD;
  1002. unsigned offset = shiftAmt / APINT_BITS_PER_WORD;
  1003. // If we are shifting whole words, just move whole words
  1004. if (wordShift == 0) {
  1005. for (unsigned i = 0; i < getNumWords() - offset; ++i)
  1006. val[i] = pVal[i+offset];
  1007. for (unsigned i = getNumWords()-offset; i < getNumWords(); i++)
  1008. val[i] = 0;
  1009. return APInt(val,BitWidth).clearUnusedBits();
  1010. }
  1011. // Shift the low order words
  1012. unsigned breakWord = getNumWords() - offset -1;
  1013. for (unsigned i = 0; i < breakWord; ++i)
  1014. val[i] = (pVal[i+offset] >> wordShift) |
  1015. (pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift));
  1016. // Shift the break word.
  1017. val[breakWord] = pVal[breakWord+offset] >> wordShift;
  1018. // Remaining words are 0
  1019. for (unsigned i = breakWord+1; i < getNumWords(); ++i)
  1020. val[i] = 0;
  1021. return APInt(val, BitWidth).clearUnusedBits();
  1022. }
  1023. /// Left-shift this APInt by shiftAmt.
  1024. /// @brief Left-shift function.
  1025. APInt APInt::shl(const APInt &shiftAmt) const {
  1026. // It's undefined behavior in C to shift by BitWidth or greater.
  1027. return shl((unsigned)shiftAmt.getLimitedValue(BitWidth));
  1028. }
  1029. APInt APInt::shlSlowCase(unsigned shiftAmt) const {
  1030. // If all the bits were shifted out, the result is 0. This avoids issues
  1031. // with shifting by the size of the integer type, which produces undefined
  1032. // results. We define these "undefined results" to always be 0.
  1033. if (shiftAmt == BitWidth)
  1034. return APInt(BitWidth, 0);
  1035. // If none of the bits are shifted out, the result is *this. This avoids a
  1036. // lshr by the words size in the loop below which can produce incorrect
  1037. // results. It also avoids the expensive computation below for a common case.
  1038. if (shiftAmt == 0)
  1039. return *this;
  1040. // Create some space for the result.
  1041. uint64_t * val = new uint64_t[getNumWords()];
  1042. // If we are shifting less than a word, do it the easy way
  1043. if (shiftAmt < APINT_BITS_PER_WORD) {
  1044. uint64_t carry = 0;
  1045. for (unsigned i = 0; i < getNumWords(); i++) {
  1046. val[i] = pVal[i] << shiftAmt | carry;
  1047. carry = pVal[i] >> (APINT_BITS_PER_WORD - shiftAmt);
  1048. }
  1049. return APInt(val, BitWidth).clearUnusedBits();
  1050. }
  1051. // Compute some values needed by the remaining shift algorithms
  1052. unsigned wordShift = shiftAmt % APINT_BITS_PER_WORD;
  1053. unsigned offset = shiftAmt / APINT_BITS_PER_WORD;
  1054. // If we are shifting whole words, just move whole words
  1055. if (wordShift == 0) {
  1056. for (unsigned i = 0; i < offset; i++)
  1057. val[i] = 0;
  1058. for (unsigned i = offset; i < getNumWords(); i++)
  1059. val[i] = pVal[i-offset];
  1060. return APInt(val,BitWidth).clearUnusedBits();
  1061. }
  1062. // Copy whole words from this to Result.
  1063. unsigned i = getNumWords() - 1;
  1064. for (; i > offset; --i)
  1065. val[i] = pVal[i-offset] << wordShift |
  1066. pVal[i-offset-1] >> (APINT_BITS_PER_WORD - wordShift);
  1067. val[offset] = pVal[0] << wordShift;
  1068. for (i = 0; i < offset; ++i)
  1069. val[i] = 0;
  1070. return APInt(val, BitWidth).clearUnusedBits();
  1071. }
  1072. APInt APInt::rotl(const APInt &rotateAmt) const {
  1073. return rotl((unsigned)rotateAmt.getLimitedValue(BitWidth));
  1074. }
  1075. APInt APInt::rotl(unsigned rotateAmt) const {
  1076. rotateAmt %= BitWidth;
  1077. if (rotateAmt == 0)
  1078. return *this;
  1079. return shl(rotateAmt) | lshr(BitWidth - rotateAmt);
  1080. }
  1081. APInt APInt::rotr(const APInt &rotateAmt) const {
  1082. return rotr((unsigned)rotateAmt.getLimitedValue(BitWidth));
  1083. }
  1084. APInt APInt::rotr(unsigned rotateAmt) const {
  1085. rotateAmt %= BitWidth;
  1086. if (rotateAmt == 0)
  1087. return *this;
  1088. return lshr(rotateAmt) | shl(BitWidth - rotateAmt);
  1089. }
  1090. // Square Root - this method computes and returns the square root of "this".
  1091. // Three mechanisms are used for computation. For small values (<= 5 bits),
  1092. // a table lookup is done. This gets some performance for common cases. For
  1093. // values using less than 52 bits, the value is converted to double and then
  1094. // the libc sqrt function is called. The result is rounded and then converted
  1095. // back to a uint64_t which is then used to construct the result. Finally,
  1096. // the Babylonian method for computing square roots is used.
  1097. APInt APInt::sqrt() const {
  1098. // Determine the magnitude of the value.
  1099. unsigned magnitude = getActiveBits();
  1100. // Use a fast table for some small values. This also gets rid of some
  1101. // rounding errors in libc sqrt for small values.
  1102. if (magnitude <= 5) {
  1103. static const uint8_t results[32] = {
  1104. /* 0 */ 0,
  1105. /* 1- 2 */ 1, 1,
  1106. /* 3- 6 */ 2, 2, 2, 2,
  1107. /* 7-12 */ 3, 3, 3, 3, 3, 3,
  1108. /* 13-20 */ 4, 4, 4, 4, 4, 4, 4, 4,
  1109. /* 21-30 */ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  1110. /* 31 */ 6
  1111. };
  1112. return APInt(BitWidth, results[ (isSingleWord() ? VAL : pVal[0]) ]);
  1113. }
  1114. // If the magnitude of the value fits in less than 52 bits (the precision of
  1115. // an IEEE double precision floating point value), then we can use the
  1116. // libc sqrt function which will probably use a hardware sqrt computation.
  1117. // This should be faster than the algorithm below.
  1118. if (magnitude < 52) {
  1119. #if HAVE_ROUND
  1120. return APInt(BitWidth,
  1121. uint64_t(::round(::sqrt(double(isSingleWord()?VAL:pVal[0])))));
  1122. #else
  1123. return APInt(BitWidth,
  1124. uint64_t(::sqrt(double(isSingleWord()?VAL:pVal[0])) + 0.5));
  1125. #endif
  1126. }
  1127. // Okay, all the short cuts are exhausted. We must compute it. The following
  1128. // is a classical Babylonian method for computing the square root. This code
  1129. // was adapted to APINt from a wikipedia article on such computations.
  1130. // See http://www.wikipedia.org/ and go to the page named
  1131. // Calculate_an_integer_square_root.
  1132. unsigned nbits = BitWidth, i = 4;
  1133. APInt testy(BitWidth, 16);
  1134. APInt x_old(BitWidth, 1);
  1135. APInt x_new(BitWidth, 0);
  1136. APInt two(BitWidth, 2);
  1137. // Select a good starting value using binary logarithms.
  1138. for (;; i += 2, testy = testy.shl(2))
  1139. if (i >= nbits || this->ule(testy)) {
  1140. x_old = x_old.shl(i / 2);
  1141. break;
  1142. }
  1143. // Use the Babylonian method to arrive at the integer square root:
  1144. for (;;) {
  1145. x_new = (this->udiv(x_old) + x_old).udiv(two);
  1146. if (x_old.ule(x_new))
  1147. break;
  1148. x_old = x_new;
  1149. }
  1150. // Make sure we return the closest approximation
  1151. // NOTE: The rounding calculation below is correct. It will produce an
  1152. // off-by-one discrepancy with results from pari/gp. That discrepancy has been
  1153. // determined to be a rounding issue with pari/gp as it begins to use a
  1154. // floating point representation after 192 bits. There are no discrepancies
  1155. // between this algorithm and pari/gp for bit widths < 192 bits.
  1156. APInt square(x_old * x_old);
  1157. APInt nextSquare((x_old + 1) * (x_old +1));
  1158. if (this->ult(square))
  1159. return x_old;
  1160. assert(this->ule(nextSquare) && "Error in APInt::sqrt computation");
  1161. APInt midpoint((nextSquare - square).udiv(two));
  1162. APInt offset(*this - square);
  1163. if (offset.ult(midpoint))
  1164. return x_old;
  1165. return x_old + 1;
  1166. }
  1167. /// Computes the multiplicative inverse of this APInt for a given modulo. The
  1168. /// iterative extended Euclidean algorithm is used to solve for this value,
  1169. /// however we simplify it to speed up calculating only the inverse, and take
  1170. /// advantage of div+rem calculations. We also use some tricks to avoid copying
  1171. /// (potentially large) APInts around.
  1172. APInt APInt::multiplicativeInverse(const APInt& modulo) const {
  1173. assert(ult(modulo) && "This APInt must be smaller than the modulo");
  1174. // Using the properties listed at the following web page (accessed 06/21/08):
  1175. // http://www.numbertheory.org/php/euclid.html
  1176. // (especially the properties numbered 3, 4 and 9) it can be proved that
  1177. // BitWidth bits suffice for all the computations in the algorithm implemented
  1178. // below. More precisely, this number of bits suffice if the multiplicative
  1179. // inverse exists, but may not suffice for the general extended Euclidean
  1180. // algorithm.
  1181. APInt r[2] = { modulo, *this };
  1182. APInt t[2] = { APInt(BitWidth, 0), APInt(BitWidth, 1) };
  1183. APInt q(BitWidth, 0);
  1184. unsigned i;
  1185. for (i = 0; r[i^1] != 0; i ^= 1) {
  1186. // An overview of the math without the confusing bit-flipping:
  1187. // q = r[i-2] / r[i-1]
  1188. // r[i] = r[i-2] % r[i-1]
  1189. // t[i] = t[i-2] - t[i-1] * q
  1190. udivrem(r[i], r[i^1], q, r[i]);
  1191. t[i] -= t[i^1] * q;
  1192. }
  1193. // If this APInt and the modulo are not coprime, there is no multiplicative
  1194. // inverse, so return 0. We check this by looking at the next-to-last
  1195. // remainder, which is the gcd(*this,modulo) as calculated by the Euclidean
  1196. // algorithm.
  1197. if (r[i] != 1)
  1198. return APInt(BitWidth, 0);
  1199. // The next-to-last t is the multiplicative inverse. However, we are
  1200. // interested in a positive inverse. Calcuate a positive one from a negative
  1201. // one if necessary. A simple addition of the modulo suffices because
  1202. // abs(t[i]) is known to be less than *this/2 (see the link above).
  1203. return t[i].isNegative() ? t[i] + modulo : t[i];
  1204. }
  1205. /// Calculate the magic numbers required to implement a signed integer division
  1206. /// by a constant as a sequence of multiplies, adds and shifts. Requires that
  1207. /// the divisor not be 0, 1, or -1. Taken from "Hacker's Delight", Henry S.
  1208. /// Warren, Jr., chapter 10.
  1209. APInt::ms APInt::magic() const {
  1210. const APInt& d = *this;
  1211. unsigned p;
  1212. APInt ad, anc, delta, q1, r1, q2, r2, t;
  1213. APInt signedMin = APInt::getSignedMinValue(d.getBitWidth());
  1214. struct ms mag;
  1215. ad = d.abs();
  1216. t = signedMin + (d.lshr(d.getBitWidth() - 1));
  1217. anc = t - 1 - t.urem(ad); // absolute value of nc
  1218. p = d.getBitWidth() - 1; // initialize p
  1219. q1 = signedMin.udiv(anc); // initialize q1 = 2p/abs(nc)
  1220. r1 = signedMin - q1*anc; // initialize r1 = rem(2p,abs(nc))
  1221. q2 = signedMin.udiv(ad); // initialize q2 = 2p/abs(d)
  1222. r2 = signedMin - q2*ad; // initialize r2 = rem(2p,abs(d))
  1223. do {
  1224. p = p + 1;
  1225. q1 = q1<<1; // update q1 = 2p/abs(nc)
  1226. r1 = r1<<1; // update r1 = rem(2p/abs(nc))
  1227. if (r1.uge(anc)) { // must be unsigned comparison
  1228. q1 = q1 + 1;
  1229. r1 = r1 - anc;
  1230. }
  1231. q2 = q2<<1; // update q2 = 2p/abs(d)
  1232. r2 = r2<<1; // update r2 = rem(2p/abs(d))
  1233. if (r2.uge(ad)) { // must be unsigned comparison
  1234. q2 = q2 + 1;
  1235. r2 = r2 - ad;
  1236. }
  1237. delta = ad - r2;
  1238. } while (q1.ult(delta) || (q1 == delta && r1 == 0));
  1239. mag.m = q2 + 1;
  1240. if (d.isNegative()) mag.m = -mag.m; // resulting magic number
  1241. mag.s = p - d.getBitWidth(); // resulting shift
  1242. return mag;
  1243. }
  1244. /// Calculate the magic numbers required to implement an unsigned integer
  1245. /// division by a constant as a sequence of multiplies, adds and shifts.
  1246. /// Requires that the divisor not be 0. Taken from "Hacker's Delight", Henry
  1247. /// S. Warren, Jr., chapter 10.
  1248. /// LeadingZeros can be used to simplify the calculation if the upper bits
  1249. /// of the divided value are known zero.
  1250. APInt::mu APInt::magicu(unsigned LeadingZeros) const {
  1251. const APInt& d = *this;
  1252. unsigned p;
  1253. APInt nc, delta, q1, r1, q2, r2;
  1254. struct mu magu;
  1255. magu.a = 0; // initialize "add" indicator
  1256. APInt allOnes = APInt::getAllOnesValue(d.getBitWidth()).lshr(LeadingZeros);
  1257. APInt signedMin = APInt::getSignedMinValue(d.getBitWidth());
  1258. APInt signedMax = APInt::getSignedMaxValue(d.getBitWidth());
  1259. nc = allOnes - (allOnes - d).urem(d);
  1260. p = d.getBitWidth() - 1; // initialize p
  1261. q1 = signedMin.udiv(nc); // initialize q1 = 2p/nc
  1262. r1 = signedMin - q1*nc; // initialize r1 = rem(2p,nc)
  1263. q2 = signedMax.udiv(d); // initialize q2 = (2p-1)/d
  1264. r2 = signedMax - q2*d; // initialize r2 = rem((2p-1),d)
  1265. do {
  1266. p = p + 1;
  1267. if (r1.uge(nc - r1)) {
  1268. q1 = q1 + q1 + 1; // update q1
  1269. r1 = r1 + r1 - nc; // update r1
  1270. }
  1271. else {
  1272. q1 = q1+q1; // update q1
  1273. r1 = r1+r1; // update r1
  1274. }
  1275. if ((r2 + 1).uge(d - r2)) {
  1276. if (q2.uge(signedMax)) magu.a = 1;
  1277. q2 = q2+q2 + 1; // update q2
  1278. r2 = r2+r2 + 1 - d; // update r2
  1279. }
  1280. else {
  1281. if (q2.uge(signedMin)) magu.a = 1;
  1282. q2 = q2+q2; // update q2
  1283. r2 = r2+r2 + 1; // update r2
  1284. }
  1285. delta = d - 1 - r2;
  1286. } while (p < d.getBitWidth()*2 &&
  1287. (q1.ult(delta) || (q1 == delta && r1 == 0)));
  1288. magu.m = q2 + 1; // resulting magic number
  1289. magu.s = p - d.getBitWidth(); // resulting shift
  1290. return magu;
  1291. }
  1292. /// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
  1293. /// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
  1294. /// variables here have the same names as in the algorithm. Comments explain
  1295. /// the algorithm and any deviation from it.
  1296. static void KnuthDiv(unsigned *u, unsigned *v, unsigned *q, unsigned* r,
  1297. unsigned m, unsigned n) {
  1298. assert(u && "Must provide dividend");
  1299. assert(v && "Must provide divisor");
  1300. assert(q && "Must provide quotient");
  1301. assert(u != v && u != q && v != q && "Must us different memory");
  1302. assert(n>1 && "n must be > 1");
  1303. // Knuth uses the value b as the base of the number system. In our case b
  1304. // is 2^31 so we just set it to -1u.
  1305. uint64_t b = uint64_t(1) << 32;
  1306. #if 0
  1307. DEBUG(dbgs() << "KnuthDiv: m=" << m << " n=" << n << '\n');
  1308. DEBUG(dbgs() << "KnuthDiv: original:");
  1309. DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
  1310. DEBUG(dbgs() << " by");
  1311. DEBUG(for (int i = n; i >0; i--) dbgs() << " " << v[i-1]);
  1312. DEBUG(dbgs() << '\n');
  1313. #endif
  1314. // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
  1315. // u and v by d. Note that we have taken Knuth's advice here to use a power
  1316. // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
  1317. // 2 allows us to shift instead of multiply and it is easy to determine the
  1318. // shift amount from the leading zeros. We are basically normalizing the u
  1319. // and v so that its high bits are shifted to the top of v's range without
  1320. // overflow. Note that this can require an extra word in u so that u must
  1321. // be of length m+n+1.
  1322. unsigned shift = countLeadingZeros(v[n-1]);
  1323. unsigned v_carry = 0;
  1324. unsigned u_carry = 0;
  1325. if (shift) {
  1326. for (unsigned i = 0; i < m+n; ++i) {
  1327. unsigned u_tmp = u[i] >> (32 - shift);
  1328. u[i] = (u[i] << shift) | u_carry;
  1329. u_carry = u_tmp;
  1330. }
  1331. for (unsigned i = 0; i < n; ++i) {
  1332. unsigned v_tmp = v[i] >> (32 - shift);
  1333. v[i] = (v[i] << shift) | v_carry;
  1334. v_carry = v_tmp;
  1335. }
  1336. }
  1337. u[m+n] = u_carry;
  1338. #if 0
  1339. DEBUG(dbgs() << "KnuthDiv: normal:");
  1340. DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
  1341. DEBUG(dbgs() << " by");
  1342. DEBUG(for (int i = n; i >0; i--) dbgs() << " " << v[i-1]);
  1343. DEBUG(dbgs() << '\n');
  1344. #endif
  1345. // D2. [Initialize j.] Set j to m. This is the loop counter over the places.
  1346. int j = m;
  1347. do {
  1348. DEBUG(dbgs() << "KnuthDiv: quotient digit #" << j << '\n');
  1349. // D3. [Calculate q'.].
  1350. // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
  1351. // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
  1352. // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
  1353. // qp by 1, inrease rp by v[n-1], and repeat this test if rp < b. The test
  1354. // on v[n-2] determines at high speed most of the cases in which the trial
  1355. // value qp is one too large, and it eliminates all cases where qp is two
  1356. // too large.
  1357. uint64_t dividend = ((uint64_t(u[j+n]) << 32) + u[j+n-1]);
  1358. DEBUG(dbgs() << "KnuthDiv: dividend == " << dividend << '\n');
  1359. uint64_t qp = dividend / v[n-1];
  1360. uint64_t rp = dividend % v[n-1];
  1361. if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
  1362. qp--;
  1363. rp += v[n-1];
  1364. if (rp < b && (qp == b || qp*v[n-2] > b*rp + u[j+n-2]))
  1365. qp--;
  1366. }
  1367. DEBUG(dbgs() << "KnuthDiv: qp == " << qp << ", rp == " << rp << '\n');
  1368. // D4. [Multiply and subtract.] Replace (u[j+n]u[j+n-1]...u[j]) with
  1369. // (u[j+n]u[j+n-1]..u[j]) - qp * (v[n-1]...v[1]v[0]). This computation
  1370. // consists of a simple multiplication by a one-place number, combined with
  1371. // a subtraction.
  1372. bool isNeg = false;
  1373. for (unsigned i = 0; i < n; ++i) {
  1374. uint64_t u_tmp = uint64_t(u[j+i]) | (uint64_t(u[j+i+1]) << 32);
  1375. uint64_t subtrahend = uint64_t(qp) * uint64_t(v[i]);
  1376. bool borrow = subtrahend > u_tmp;
  1377. DEBUG(dbgs() << "KnuthDiv: u_tmp == " << u_tmp
  1378. << ", subtrahend == " << subtrahend
  1379. << ", borrow = " << borrow << '\n');
  1380. uint64_t result = u_tmp - subtrahend;
  1381. unsigned k = j + i;
  1382. u[k++] = (unsigned)(result & (b-1)); // subtract low word
  1383. u[k++] = (unsigned)(result >> 32); // subtract high word
  1384. while (borrow && k <= m+n) { // deal with borrow to the left
  1385. borrow = u[k] == 0;
  1386. u[k]--;
  1387. k++;
  1388. }
  1389. isNeg |= borrow;
  1390. DEBUG(dbgs() << "KnuthDiv: u[j+i] == " << u[j+i] << ", u[j+i+1] == " <<
  1391. u[j+i+1] << '\n');
  1392. }
  1393. DEBUG(dbgs() << "KnuthDiv: after subtraction:");
  1394. DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
  1395. DEBUG(dbgs() << '\n');
  1396. // The digits (u[j+n]...u[j]) should be kept positive; if the result of
  1397. // this step is actually negative, (u[j+n]...u[j]) should be left as the
  1398. // true value plus b**(n+1), namely as the b's complement of
  1399. // the true value, and a "borrow" to the left should be remembered.
  1400. //
  1401. if (isNeg) {
  1402. bool carry = true; // true because b's complement is "complement + 1"
  1403. for (unsigned i = 0; i <= m+n; ++i) {
  1404. u[i] = ~u[i] + carry; // b's complement
  1405. carry = carry && u[i] == 0;
  1406. }
  1407. }
  1408. DEBUG(dbgs() << "KnuthDiv: after complement:");
  1409. DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
  1410. DEBUG(dbgs() << '\n');
  1411. // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was
  1412. // negative, go to step D6; otherwise go on to step D7.
  1413. q[j] = (unsigned)qp;
  1414. if (isNeg) {
  1415. // D6. [Add back]. The probability that this step is necessary is very
  1416. // small, on the order of only 2/b. Make sure that test data accounts for
  1417. // this possibility. Decrease q[j] by 1
  1418. q[j]--;
  1419. // and add (0v[n-1]...v[1]v[0]) to (u[j+n]u[j+n-1]...u[j+1]u[j]).
  1420. // A carry will occur to the left of u[j+n], and it should be ignored
  1421. // since it cancels with the borrow that occurred in D4.
  1422. bool carry = false;
  1423. for (unsigned i = 0; i < n; i++) {
  1424. unsigned limit = std::min(u[j+i],v[i]);
  1425. u[j+i] += v[i] + carry;
  1426. carry = u[j+i] < limit || (carry && u[j+i] == limit);
  1427. }
  1428. u[j+n] += carry;
  1429. }
  1430. DEBUG(dbgs() << "KnuthDiv: after correction:");
  1431. DEBUG(for (int i = m+n; i >=0; i--) dbgs() <<" " << u[i]);
  1432. DEBUG(dbgs() << "\nKnuthDiv: digit result = " << q[j] << '\n');
  1433. // D7. [Loop on j.] Decrease j by one. Now if j >= 0, go back to D3.
  1434. } while (--j >= 0);
  1435. DEBUG(dbgs() << "KnuthDiv: quotient:");
  1436. DEBUG(for (int i = m; i >=0; i--) dbgs() <<" " << q[i]);
  1437. DEBUG(dbgs() << '\n');
  1438. // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
  1439. // remainder may be obtained by dividing u[...] by d. If r is non-null we
  1440. // compute the remainder (urem uses this).
  1441. if (r) {
  1442. // The value d is expressed by the "shift" value above since we avoided
  1443. // multiplication by d by using a shift left. So, all we have to do is
  1444. // shift right here. In order to mak
  1445. if (shift) {
  1446. unsigned carry = 0;
  1447. DEBUG(dbgs() << "KnuthDiv: remainder:");
  1448. for (int i = n-1; i >= 0; i--) {
  1449. r[i] = (u[i] >> shift) | carry;
  1450. carry = u[i] << (32 - shift);
  1451. DEBUG(dbgs() << " " << r[i]);
  1452. }
  1453. } else {
  1454. for (int i = n-1; i >= 0; i--) {
  1455. r[i] = u[i];
  1456. DEBUG(dbgs() << " " << r[i]);
  1457. }
  1458. }
  1459. DEBUG(dbgs() << '\n');
  1460. }
  1461. #if 0
  1462. DEBUG(dbgs() << '\n');
  1463. #endif
  1464. }
  1465. void APInt::divide(const APInt LHS, unsigned lhsWords,
  1466. const APInt &RHS, unsigned rhsWords,
  1467. APInt *Quotient, APInt *Remainder)
  1468. {
  1469. assert(lhsWords >= rhsWords && "Fractional result");
  1470. // First, compose the values into an array of 32-bit words instead of
  1471. // 64-bit words. This is a necessity of both the "short division" algorithm
  1472. // and the Knuth "classical algorithm" which requires there to be native
  1473. // operations for +, -, and * on an m bit value with an m*2 bit result. We
  1474. // can't use 64-bit operands here because we don't have native results of
  1475. // 128-bits. Furthermore, casting the 64-bit values to 32-bit values won't
  1476. // work on large-endian machines.
  1477. uint64_t mask = ~0ull >> (sizeof(unsigned)*CHAR_BIT);
  1478. unsigned n = rhsWords * 2;
  1479. unsigned m = (lhsWords * 2) - n;
  1480. // Allocate space for the temporary values we need either on the stack, if
  1481. // it will fit, or on the heap if it won't.
  1482. unsigned SPACE[128];
  1483. unsigned *U = 0;
  1484. unsigned *V = 0;
  1485. unsigned *Q = 0;
  1486. unsigned *R = 0;
  1487. if ((Remainder?4:3)*n+2*m+1 <= 128) {
  1488. U = &SPACE[0];
  1489. V = &SPACE[m+n+1];
  1490. Q = &SPACE[(m+n+1) + n];
  1491. if (Remainder)
  1492. R = &SPACE[(m+n+1) + n + (m+n)];
  1493. } else {
  1494. U = new unsigned[m + n + 1];
  1495. V = new unsigned[n];
  1496. Q = new unsigned[m+n];
  1497. if (Remainder)
  1498. R = new unsigned[n];
  1499. }
  1500. // Initialize the dividend
  1501. memset(U, 0, (m+n+1)*sizeof(unsigned));
  1502. for (unsigned i = 0; i < lhsWords; ++i) {
  1503. uint64_t tmp = (LHS.getNumWords() == 1 ? LHS.VAL : LHS.pVal[i]);
  1504. U[i * 2] = (unsigned)(tmp & mask);
  1505. U[i * 2 + 1] = (unsigned)(tmp >> (sizeof(unsigned)*CHAR_BIT));
  1506. }
  1507. U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
  1508. // Initialize the divisor
  1509. memset(V, 0, (n)*sizeof(unsigned));
  1510. for (unsigned i = 0; i < rhsWords; ++i) {
  1511. uint64_t tmp = (RHS.getNumWords() == 1 ? RHS.VAL : RHS.pVal[i]);
  1512. V[i * 2] = (unsigned)(tmp & mask);
  1513. V[i * 2 + 1] = (unsigned)(tmp >> (sizeof(unsigned)*CHAR_BIT));
  1514. }
  1515. // initialize the quotient and remainder
  1516. memset(Q, 0, (m+n) * sizeof(unsigned));
  1517. if (Remainder)
  1518. memset(R, 0, n * sizeof(unsigned));
  1519. // Now, adjust m and n for the Knuth division. n is the number of words in
  1520. // the divisor. m is the number of words by which the dividend exceeds the
  1521. // divisor (i.e. m+n is the length of the dividend). These sizes must not
  1522. // contain any zero words or the Knuth algorithm fails.
  1523. for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
  1524. n--;
  1525. m++;
  1526. }
  1527. for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
  1528. m--;
  1529. // If we're left with only a single word for the divisor, Knuth doesn't work
  1530. // so we implement the short division algorithm here. This is much simpler
  1531. // and faster because we are certain that we can divide a 64-bit quantity
  1532. // by a 32-bit quantity at hardware speed and short division is simply a
  1533. // series of such operations. This is just like doing short division but we
  1534. // are using base 2^32 instead of base 10.
  1535. assert(n != 0 && "Divide by zero?");
  1536. if (n == 1) {
  1537. unsigned divisor = V[0];
  1538. unsigned remainder = 0;
  1539. for (int i = m+n-1; i >= 0; i--) {
  1540. uint64_t partial_dividend = uint64_t(remainder) << 32 | U[i];
  1541. if (partial_dividend == 0) {
  1542. Q[i] = 0;
  1543. remainder = 0;
  1544. } else if (partial_dividend < divisor) {
  1545. Q[i] = 0;
  1546. remainder = (unsigned)partial_dividend;
  1547. } else if (partial_dividend == divisor) {
  1548. Q[i] = 1;
  1549. remainder = 0;
  1550. } else {
  1551. Q[i] = (unsigned)(partial_dividend / divisor);
  1552. remainder = (unsigned)(partial_dividend - (Q[i] * divisor));
  1553. }
  1554. }
  1555. if (R)
  1556. R[0] = remainder;
  1557. } else {
  1558. // Now we're ready to invoke the Knuth classical divide algorithm. In this
  1559. // case n > 1.
  1560. KnuthDiv(U, V, Q, R, m, n);
  1561. }
  1562. // If the caller wants the quotient
  1563. if (Quotient) {
  1564. // Set up the Quotient value's memory.
  1565. if (Quotient->BitWidth != LHS.BitWidth) {
  1566. if (Quotient->isSingleWord())
  1567. Quotient->VAL = 0;
  1568. else
  1569. delete [] Quotient->pVal;
  1570. Quotient->BitWidth = LHS.BitWidth;
  1571. if (!Quotient->isSingleWord())
  1572. Quotient->pVal = getClearedMemory(Quotient->getNumWords());
  1573. } else
  1574. Quotient->clearAllBits();
  1575. // The quotient is in Q. Reconstitute the quotient into Quotient's low
  1576. // order words.
  1577. if (lhsWords == 1) {
  1578. uint64_t tmp =
  1579. uint64_t(Q[0]) | (uint64_t(Q[1]) << (APINT_BITS_PER_WORD / 2));
  1580. if (Quotient->isSingleWord())
  1581. Quotient->VAL = tmp;
  1582. else
  1583. Quotient->pVal[0] = tmp;
  1584. } else {
  1585. assert(!Quotient->isSingleWord() && "Quotient APInt not large enough");
  1586. for (unsigned i = 0; i < lhsWords; ++i)
  1587. Quotient->pVal[i] =
  1588. uint64_t(Q[i*2]) | (uint64_t(Q[i*2+1]) << (APINT_BITS_PER_WORD / 2));
  1589. }
  1590. }
  1591. // If the caller wants the remainder
  1592. if (Remainder) {
  1593. // Set up the Remainder value's memory.
  1594. if (Remainder->BitWidth != RHS.BitWidth) {
  1595. if (Remainder->isSingleWord())
  1596. Remainder->VAL = 0;
  1597. else
  1598. delete [] Remainder->pVal;
  1599. Remainder->BitWidth = RHS.BitWidth;
  1600. if (!Remainder->isSingleWord())
  1601. Remainder->pVal = getClearedMemory(Remainder->getNumWords());
  1602. } else
  1603. Remainder->clearAllBits();
  1604. // The remainder is in R. Reconstitute the remainder into Remainder's low
  1605. // order words.
  1606. if (rhsWords == 1) {
  1607. uint64_t tmp =
  1608. uint64_t(R[0]) | (uint64_t(R[1]) << (APINT_BITS_PER_WORD / 2));
  1609. if (Remainder->isSingleWord())
  1610. Remainder->VAL = tmp;
  1611. else
  1612. Remainder->pVal[0] = tmp;
  1613. } else {
  1614. assert(!Remainder->isSingleWord() && "Remainder APInt not large enough");
  1615. for (unsigned i = 0; i < rhsWords; ++i)
  1616. Remainder->pVal[i] =
  1617. uint64_t(R[i*2]) | (uint64_t(R[i*2+1]) << (APINT_BITS_PER_WORD / 2));
  1618. }
  1619. }
  1620. // Clean up the memory we allocated.
  1621. if (U != &SPACE[0]) {
  1622. delete [] U;
  1623. delete [] V;
  1624. delete [] Q;
  1625. delete [] R;
  1626. }
  1627. }
  1628. APInt APInt::udiv(const APInt& RHS) const {
  1629. assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
  1630. // First, deal with the easy case
  1631. if (isSingleWord()) {
  1632. assert(RHS.VAL != 0 && "Divide by zero?");
  1633. return APInt(BitWidth, VAL / RHS.VAL);
  1634. }
  1635. // Get some facts about the LHS and RHS number of bits and words
  1636. unsigned rhsBits = RHS.getActiveBits();
  1637. unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
  1638. assert(rhsWords && "Divided by zero???");
  1639. unsigned lhsBits = this->getActiveBits();
  1640. unsigned lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
  1641. // Deal with some degenerate cases
  1642. if (!lhsWords)
  1643. // 0 / X ===> 0
  1644. return APInt(BitWidth, 0);
  1645. else if (lhsWords < rhsWords || this->ult(RHS)) {
  1646. // X / Y ===> 0, iff X < Y
  1647. return APInt(BitWidth, 0);
  1648. } else if (*this == RHS) {
  1649. // X / X ===> 1
  1650. return APInt(BitWidth, 1);
  1651. } else if (lhsWords == 1 && rhsWords == 1) {
  1652. // All high words are zero, just use native divide
  1653. return APInt(BitWidth, this->pVal[0] / RHS.pVal[0]);
  1654. }
  1655. // We have to compute it the hard way. Invoke the Knuth divide algorithm.
  1656. APInt Quotient(1,0); // to hold result.
  1657. divide(*this, lhsWords, RHS, rhsWords, &Quotient, 0);
  1658. return Quotient;
  1659. }
  1660. APInt APInt::sdiv(const APInt &RHS) const {
  1661. if (isNegative()) {
  1662. if (RHS.isNegative())
  1663. return (-(*this)).udiv(-RHS);
  1664. return -((-(*this)).udiv(RHS));
  1665. }
  1666. if (RHS.isNegative())
  1667. return -(this->udiv(-RHS));
  1668. return this->udiv(RHS);
  1669. }
  1670. APInt APInt::urem(const APInt& RHS) const {
  1671. assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
  1672. if (isSingleWord()) {
  1673. assert(RHS.VAL != 0 && "Remainder by zero?");
  1674. return APInt(BitWidth, VAL % RHS.VAL);
  1675. }
  1676. // Get some facts about the LHS
  1677. unsigned lhsBits = getActiveBits();
  1678. unsigned lhsWords = !lhsBits ? 0 : (whichWord(lhsBits - 1) + 1);
  1679. // Get some facts about the RHS
  1680. unsigned rhsBits = RHS.getActiveBits();
  1681. unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
  1682. assert(rhsWords && "Performing remainder operation by zero ???");
  1683. // Check the degenerate cases
  1684. if (lhsWords == 0) {
  1685. // 0 % Y ===> 0
  1686. return APInt(BitWidth, 0);
  1687. } else if (lhsWords < rhsWords || this->ult(RHS)) {
  1688. // X % Y ===> X, iff X < Y
  1689. return *this;
  1690. } else if (*this == RHS) {
  1691. // X % X == 0;
  1692. return APInt(BitWidth, 0);
  1693. } else if (lhsWords == 1) {
  1694. // All high words are zero, just use native remainder
  1695. return APInt(BitWidth, pVal[0] % RHS.pVal[0]);
  1696. }
  1697. // We have to compute it the hard way. Invoke the Knuth divide algorithm.
  1698. APInt Remainder(1,0);
  1699. divide(*this, lhsWords, RHS, rhsWords, 0, &Remainder);
  1700. return Remainder;
  1701. }
  1702. APInt APInt::srem(const APInt &RHS) const {
  1703. if (isNegative()) {
  1704. if (RHS.isNegative())
  1705. return -((-(*this)).urem(-RHS));
  1706. return -((-(*this)).urem(RHS));
  1707. }
  1708. if (RHS.isNegative())
  1709. return this->urem(-RHS);
  1710. return this->urem(RHS);
  1711. }
  1712. void APInt::udivrem(const APInt &LHS, const APInt &RHS,
  1713. APInt &Quotient, APInt &Remainder) {
  1714. // Get some size facts about the dividend and divisor
  1715. unsigned lhsBits = LHS.getActiveBits();
  1716. unsigned lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
  1717. unsigned rhsBits = RHS.getActiveBits();
  1718. unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
  1719. // Check the degenerate cases
  1720. if (lhsWords == 0) {
  1721. Quotient = 0; // 0 / Y ===> 0
  1722. Remainder = 0; // 0 % Y ===> 0
  1723. return;
  1724. }
  1725. if (lhsWords < rhsWords || LHS.ult(RHS)) {
  1726. Remainder = LHS; // X % Y ===> X, iff X < Y
  1727. Quotient = 0; // X / Y ===> 0, iff X < Y
  1728. return;
  1729. }
  1730. if (LHS == RHS) {
  1731. Quotient = 1; // X / X ===> 1
  1732. Remainder = 0; // X % X ===> 0;
  1733. return;
  1734. }
  1735. if (lhsWords == 1 && rhsWords == 1) {
  1736. // There is only one word to consider so use the native versions.
  1737. uint64_t lhsValue = LHS.isSingleWord() ? LHS.VAL : LHS.pVal[0];
  1738. uint64_t rhsValue = RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
  1739. Quotient = APInt(LHS.getBitWidth(), lhsValue / rhsValue);
  1740. Remainder = APInt(LHS.getBitWidth(), lhsValue % rhsValue);
  1741. return;
  1742. }
  1743. // Okay, lets do it the long way
  1744. divide(LHS, lhsWords, RHS, rhsWords, &Quotient, &Remainder);
  1745. }
  1746. void APInt::sdivrem(const APInt &LHS, const APInt &RHS,
  1747. APInt &Quotient, APInt &Remainder) {
  1748. if (LHS.isNegative()) {
  1749. if (RHS.isNegative())
  1750. APInt::udivrem(-LHS, -RHS, Quotient, Remainder);
  1751. else {
  1752. APInt::udivrem(-LHS, RHS, Quotient, Remainder);
  1753. Quotient = -Quotient;
  1754. }
  1755. Remainder = -Remainder;
  1756. } else if (RHS.isNegative()) {
  1757. APInt::udivrem(LHS, -RHS, Quotient, Remainder);
  1758. Quotient = -Quotient;
  1759. } else {
  1760. APInt::udivrem(LHS, RHS, Quotient, Remainder);
  1761. }
  1762. }
  1763. APInt APInt::sadd_ov(const APInt &RHS, bool &Overflow) const {
  1764. APInt Res = *this+RHS;
  1765. Overflow = isNonNegative() == RHS.isNonNegative() &&
  1766. Res.isNonNegative() != isNonNegative();
  1767. return Res;
  1768. }
  1769. APInt APInt::uadd_ov(const APInt &RHS, bool &Overflow) const {
  1770. APInt Res = *this+RHS;
  1771. Overflow = Res.ult(RHS);
  1772. return Res;
  1773. }
  1774. APInt APInt::ssub_ov(const APInt &RHS, bool &Overflow) const {
  1775. APInt Res = *this - RHS;
  1776. Overflow = isNonNegative() != RHS.isNonNegative() &&
  1777. Res.isNonNegative() != isNonNegative();
  1778. return Res;
  1779. }
  1780. APInt APInt::usub_ov(const APInt &RHS, bool &Overflow) const {
  1781. APInt Res = *this-RHS;
  1782. Overflow = Res.ugt(*this);
  1783. return Res;
  1784. }
  1785. APInt APInt::sdiv_ov(const APInt &RHS, bool &Overflow) const {
  1786. // MININT/-1 --> overflow.
  1787. Overflow = isMinSignedValue() && RHS.isAllOnesValue();
  1788. return sdiv(RHS);
  1789. }
  1790. APInt APInt::smul_ov(const APInt &RHS, bool &Overflow) const {
  1791. APInt Res = *this * RHS;
  1792. if (*this != 0 && RHS != 0)
  1793. Overflow = Res.sdiv(RHS) != *this || Res.sdiv(*this) != RHS;
  1794. else
  1795. Overflow = false;
  1796. return Res;
  1797. }
  1798. APInt APInt::umul_ov(const APInt &RHS, bool &Overflow) const {
  1799. APInt Res = *this * RHS;
  1800. if (*this != 0 && RHS != 0)
  1801. Overflow = Res.udiv(RHS) != *this || Res.udiv(*this) != RHS;
  1802. else
  1803. Overflow = false;
  1804. return Res;
  1805. }
  1806. APInt APInt::sshl_ov(unsigned ShAmt, bool &Overflow) const {
  1807. Overflow = ShAmt >= getBitWidth();
  1808. if (Overflow)
  1809. ShAmt = getBitWidth()-1;
  1810. if (isNonNegative()) // Don't allow sign change.
  1811. Overflow = ShAmt >= countLeadingZeros();
  1812. else
  1813. Overflow = ShAmt >= countLeadingOnes();
  1814. return *this << ShAmt;
  1815. }
  1816. void APInt::fromString(unsigned numbits, StringRef str, uint8_t radix) {
  1817. // Check our assumptions here
  1818. assert(!str.empty() && "Invalid string length");
  1819. assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 ||
  1820. radix == 36) &&
  1821. "Radix should be 2, 8, 10, 16, or 36!");
  1822. StringRef::iterator p = str.begin();
  1823. size_t slen = str.size();
  1824. bool isNeg = *p == '-';
  1825. if (*p == '-' || *p == '+') {
  1826. p++;
  1827. slen--;
  1828. assert(slen && "String is only a sign, needs a value.");
  1829. }
  1830. assert((slen <= numbits || radix != 2) && "Insufficient bit width");
  1831. assert(((slen-1)*3 <= numbits || radix != 8) && "Insufficient bit width");
  1832. assert(((slen-1)*4 <= numbits || radix != 16) && "Insufficient bit width");
  1833. assert((((slen-1)*64)/22 <= numbits || radix != 10) &&
  1834. "Insufficient bit width");
  1835. // Allocate memory
  1836. if (!isSingleWord())
  1837. pVal = getClearedMemory(getNumWords());
  1838. // Figure out if we can shift instead of multiply
  1839. unsigned shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0);
  1840. // Set up an APInt for the digit to add outside the loop so we don't
  1841. // constantly construct/destruct it.
  1842. APInt apdigit(getBitWidth(), 0);
  1843. APInt apradix(getBitWidth(), radix);
  1844. // Enter digit traversal loop
  1845. for (StringRef::iterator e = str.end(); p != e; ++p) {
  1846. unsigned digit = getDigit(*p, radix);
  1847. assert(digit < radix && "Invalid character in digit string");
  1848. // Shift or multiply the value by the radix
  1849. if (slen > 1) {
  1850. if (shift)
  1851. *this <<= shift;
  1852. else
  1853. *this *= apradix;
  1854. }
  1855. // Add in the digit we just interpreted
  1856. if (apdigit.isSingleWord())
  1857. apdigit.VAL = digit;
  1858. else
  1859. apdigit.pVal[0] = digit;
  1860. *this += apdigit;
  1861. }
  1862. // If its negative, put it in two's complement form
  1863. if (isNeg) {
  1864. --(*this);
  1865. this->flipAllBits();
  1866. }
  1867. }
  1868. void APInt::toString(SmallVectorImpl<char> &Str, unsigned Radix,
  1869. bool Signed, bool formatAsCLiteral) const {
  1870. assert((Radix == 10 || Radix == 8 || Radix == 16 || Radix == 2 ||
  1871. Radix == 36) &&
  1872. "Radix should be 2, 8, 10, 16, or 36!");
  1873. const char *Prefix = "";
  1874. if (formatAsCLiteral) {
  1875. switch (Radix) {
  1876. case 2:
  1877. // Binary literals are a non-standard extension added in gcc 4.3:
  1878. // http://gcc.gnu.org/onlinedocs/gcc-4.3.0/gcc/Binary-constants.html
  1879. Prefix = "0b";
  1880. break;
  1881. case 8:
  1882. Prefix = "0";
  1883. break;
  1884. case 10:
  1885. break; // No prefix
  1886. case 16:
  1887. Prefix = "0x";
  1888. break;
  1889. default:
  1890. llvm_unreachable("Invalid radix!");
  1891. }
  1892. }
  1893. // First, check for a zero value and just short circuit the logic below.
  1894. if (*this == 0) {
  1895. while (*Prefix) {
  1896. Str.push_back(*Prefix);
  1897. ++Prefix;
  1898. };
  1899. Str.push_back('0');
  1900. return;
  1901. }
  1902. static const char Digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  1903. if (isSingleWord()) {
  1904. char Buffer[65];
  1905. char *BufPtr = Buffer+65;
  1906. uint64_t N;
  1907. if (!Signed) {
  1908. N = getZExtValue();
  1909. } else {
  1910. int64_t I = getSExtValue();
  1911. if (I >= 0) {
  1912. N = I;
  1913. } else {
  1914. Str.push_back('-');
  1915. N = -(uint64_t)I;
  1916. }
  1917. }
  1918. while (*Prefix) {
  1919. Str.push_back(*Prefix);
  1920. ++Prefix;
  1921. };
  1922. while (N) {
  1923. *--BufPtr = Digits[N % Radix];
  1924. N /= Radix;
  1925. }
  1926. Str.append(BufPtr, Buffer+65);
  1927. return;
  1928. }
  1929. APInt Tmp(*this);
  1930. if (Signed && isNegative()) {
  1931. // They want to print the signed version and it is a negative value
  1932. // Flip the bits and add one to turn it into the equivalent positive
  1933. // value and put a '-' in the result.
  1934. Tmp.flipAllBits();
  1935. ++Tmp;
  1936. Str.push_back('-');
  1937. }
  1938. while (*Prefix) {
  1939. Str.push_back(*Prefix);
  1940. ++Prefix;
  1941. };
  1942. // We insert the digits backward, then reverse them to get the right order.
  1943. unsigned StartDig = Str.size();
  1944. // For the 2, 8 and 16 bit cases, we can just shift instead of divide
  1945. // because the number of bits per digit (1, 3 and 4 respectively) divides
  1946. // equaly. We just shift until the value is zero.
  1947. if (Radix == 2 || Radix == 8 || Radix == 16) {
  1948. // Just shift tmp right for each digit width until it becomes zero
  1949. unsigned ShiftAmt = (Radix == 16 ? 4 : (Radix == 8 ? 3 : 1));
  1950. unsigned MaskAmt = Radix - 1;
  1951. while (Tmp != 0) {
  1952. unsigned Digit = unsigned(Tmp.getRawData()[0]) & MaskAmt;
  1953. Str.push_back(Digits[Digit]);
  1954. Tmp = Tmp.lshr(ShiftAmt);
  1955. }
  1956. } else {
  1957. APInt divisor(Radix == 10? 4 : 8, Radix);
  1958. while (Tmp != 0) {
  1959. APInt APdigit(1, 0);
  1960. APInt tmp2(Tmp.getBitWidth(), 0);
  1961. divide(Tmp, Tmp.getNumWords(), divisor, divisor.getNumWords(), &tmp2,
  1962. &APdigit);
  1963. unsigned Digit = (unsigned)APdigit.getZExtValue();
  1964. assert(Digit < Radix && "divide failed");
  1965. Str.push_back(Digits[Digit]);
  1966. Tmp = tmp2;
  1967. }
  1968. }
  1969. // Reverse the digits before returning.
  1970. std::reverse(Str.begin()+StartDig, Str.end());
  1971. }
  1972. /// toString - This returns the APInt as a std::string. Note that this is an
  1973. /// inefficient method. It is better to pass in a SmallVector/SmallString
  1974. /// to the methods above.
  1975. std::string APInt::toString(unsigned Radix = 10, bool Signed = true) const {
  1976. SmallString<40> S;
  1977. toString(S, Radix, Signed, /* formatAsCLiteral = */false);
  1978. return S.str();
  1979. }
  1980. void APInt::dump() const {
  1981. SmallString<40> S, U;
  1982. this->toStringUnsigned(U);
  1983. this->toStringSigned(S);
  1984. dbgs() << "APInt(" << BitWidth << "b, "
  1985. << U.str() << "u " << S.str() << "s)";
  1986. }
  1987. void APInt::print(raw_ostream &OS, bool isSigned) const {
  1988. SmallString<40> S;
  1989. this->toString(S, 10, isSigned, /* formatAsCLiteral = */false);
  1990. OS << S.str();
  1991. }
  1992. // This implements a variety of operations on a representation of
  1993. // arbitrary precision, two's-complement, bignum integer values.
  1994. // Assumed by lowHalf, highHalf, partMSB and partLSB. A fairly safe
  1995. // and unrestricting assumption.
  1996. #define COMPILE_TIME_ASSERT(cond) extern int CTAssert[(cond) ? 1 : -1]
  1997. COMPILE_TIME_ASSERT(integerPartWidth % 2 == 0);
  1998. /* Some handy functions local to this file. */
  1999. namespace {
  2000. /* Returns the integer part with the least significant BITS set.
  2001. BITS cannot be zero. */
  2002. static inline integerPart
  2003. lowBitMask(unsigned int bits)
  2004. {
  2005. assert(bits != 0 && bits <= integerPartWidth);
  2006. return ~(integerPart) 0 >> (integerPartWidth - bits);
  2007. }
  2008. /* Returns the value of the lower half of PART. */
  2009. static inline integerPart
  2010. lowHalf(integerPart part)
  2011. {
  2012. return part & lowBitMask(integerPartWidth / 2);
  2013. }
  2014. /* Returns the value of the upper half of PART. */
  2015. static inline integerPart
  2016. highHalf(integerPart part)
  2017. {
  2018. return part >> (integerPartWidth / 2);
  2019. }
  2020. /* Returns the bit number of the most significant set bit of a part.
  2021. If the input number has no bits set -1U is returned. */
  2022. static unsigned int
  2023. partMSB(integerPart value)
  2024. {
  2025. return findLastSet(value, ZB_Max);
  2026. }
  2027. /* Returns the bit number of the least significant set bit of a
  2028. part. If the input number has no bits set -1U is returned. */
  2029. static unsigned int
  2030. partLSB(integerPart value)
  2031. {
  2032. return findFirstSet(value, ZB_Max);
  2033. }
  2034. }
  2035. /* Sets the least significant part of a bignum to the input value, and
  2036. zeroes out higher parts. */
  2037. void
  2038. APInt::tcSet(integerPart *dst, integerPart part, unsigned int parts)
  2039. {
  2040. unsigned int i;
  2041. assert(parts > 0);
  2042. dst[0] = part;
  2043. for (i = 1; i < parts; i++)
  2044. dst[i] = 0;
  2045. }
  2046. /* Assign one bignum to another. */
  2047. void
  2048. APInt::tcAssign(integerPart *dst, const integerPart *src, unsigned int parts)
  2049. {
  2050. unsigned int i;
  2051. for (i = 0; i < parts; i++)
  2052. dst[i] = src[i];
  2053. }
  2054. /* Returns true if a bignum is zero, false otherwise. */
  2055. bool
  2056. APInt::tcIsZero(const integerPart *src, unsigned int parts)
  2057. {
  2058. unsigned int i;
  2059. for (i = 0; i < parts; i++)
  2060. if (src[i])
  2061. return false;
  2062. return true;
  2063. }
  2064. /* Extract the given bit of a bignum; returns 0 or 1. */
  2065. int
  2066. APInt::tcExtractBit(const integerPart *parts, unsigned int bit)
  2067. {
  2068. return (parts[bit / integerPartWidth] &
  2069. ((integerPart) 1 << bit % integerPartWidth)) != 0;
  2070. }
  2071. /* Set the given bit of a bignum. */
  2072. void
  2073. APInt::tcSetBit(integerPart *parts, unsigned int bit)
  2074. {
  2075. parts[bit / integerPartWidth] |= (integerPart) 1 << (bit % integerPartWidth);
  2076. }
  2077. /* Clears the given bit of a bignum. */
  2078. void
  2079. APInt::tcClearBit(integerPart *parts, unsigned int bit)
  2080. {
  2081. parts[bit / integerPartWidth] &=
  2082. ~((integerPart) 1 << (bit % integerPartWidth));
  2083. }
  2084. /* Returns the bit number of the least significant set bit of a
  2085. number. If the input number has no bits set -1U is returned. */
  2086. unsigned int
  2087. APInt::tcLSB(const integerPart *parts, unsigned int n)
  2088. {
  2089. unsigned int i, lsb;
  2090. for (i = 0; i < n; i++) {
  2091. if (parts[i] != 0) {
  2092. lsb = partLSB(parts[i]);
  2093. return lsb + i * integerPartWidth;
  2094. }
  2095. }
  2096. return -1U;
  2097. }
  2098. /* Returns the bit number of the most significant set bit of a number.
  2099. If the input number has no bits set -1U is returned. */
  2100. unsigned int
  2101. APInt::tcMSB(const integerPart *parts, unsigned int n)
  2102. {
  2103. unsigned int msb;
  2104. do {
  2105. --n;
  2106. if (parts[n] != 0) {
  2107. msb = partMSB(parts[n]);
  2108. return msb + n * integerPartWidth;
  2109. }
  2110. } while (n);
  2111. return -1U;
  2112. }
  2113. /* Copy the bit vector of width srcBITS from SRC, starting at bit
  2114. srcLSB, to DST, of dstCOUNT parts, such that the bit srcLSB becomes
  2115. the least significant bit of DST. All high bits above srcBITS in
  2116. DST are zero-filled. */
  2117. void
  2118. APInt::tcExtract(integerPart *dst, unsigned int dstCount,const integerPart *src,
  2119. unsigned int srcBits, unsigned int srcLSB)
  2120. {
  2121. unsigned int firstSrcPart, dstParts, shift, n;
  2122. dstParts = (srcBits + integerPartWidth - 1) / integerPartWidth;
  2123. assert(dstParts <= dstCount);
  2124. firstSrcPart = srcLSB / integerPartWidth;
  2125. tcAssign (dst, src + firstSrcPart, dstParts);
  2126. shift = srcLSB % integerPartWidth;
  2127. tcShiftRight (dst, dstParts, shift);
  2128. /* We now have (dstParts * integerPartWidth - shift) bits from SRC
  2129. in DST. If this is less that srcBits, append the rest, else
  2130. clear the high bits. */
  2131. n = dstParts * integerPartWidth - shift;
  2132. if (n < srcBits) {
  2133. integerPart mask = lowBitMask (srcBits - n);
  2134. dst[dstParts - 1] |= ((src[firstSrcPart + dstParts] & mask)
  2135. << n % integerPartWidth);
  2136. } else if (n > srcBits) {
  2137. if (srcBits % integerPartWidth)
  2138. dst[dstParts - 1] &= lowBitMask (srcBits % integerPartWidth);
  2139. }
  2140. /* Clear high parts. */
  2141. while (dstParts < dstCount)
  2142. dst[dstParts++] = 0;
  2143. }
  2144. /* DST += RHS + C where C is zero or one. Returns the carry flag. */
  2145. integerPart
  2146. APInt::tcAdd(integerPart *dst, const integerPart *rhs,
  2147. integerPart c, unsigned int parts)
  2148. {
  2149. unsigned int i;
  2150. assert(c <= 1);
  2151. for (i = 0; i < parts; i++) {
  2152. integerPart l;
  2153. l = dst[i];
  2154. if (c) {
  2155. dst[i] += rhs[i] + 1;
  2156. c = (dst[i] <= l);
  2157. } else {
  2158. dst[i] += rhs[i];
  2159. c = (dst[i] < l);
  2160. }
  2161. }
  2162. return c;
  2163. }
  2164. /* DST -= RHS + C where C is zero or one. Returns the carry flag. */
  2165. integerPart
  2166. APInt::tcSubtract(integerPart *dst, const integerPart *rhs,
  2167. integerPart c, unsigned int parts)
  2168. {
  2169. unsigned int i;
  2170. assert(c <= 1);
  2171. for (i = 0; i < parts; i++) {
  2172. integerPart l;
  2173. l = dst[i];
  2174. if (c) {
  2175. dst[i] -= rhs[i] + 1;
  2176. c = (dst[i] >= l);
  2177. } else {
  2178. dst[i] -= rhs[i];
  2179. c = (dst[i] > l);
  2180. }
  2181. }
  2182. return c;
  2183. }
  2184. /* Negate a bignum in-place. */
  2185. void
  2186. APInt::tcNegate(integerPart *dst, unsigned int parts)
  2187. {
  2188. tcComplement(dst, parts);
  2189. tcIncrement(dst, parts);
  2190. }
  2191. /* DST += SRC * MULTIPLIER + CARRY if add is true
  2192. DST = SRC * MULTIPLIER + CARRY if add is false
  2193. Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC
  2194. they must start at the same point, i.e. DST == SRC.
  2195. If DSTPARTS == SRCPARTS + 1 no overflow occurs and zero is
  2196. returned. Otherwise DST is filled with the least significant
  2197. DSTPARTS parts of the result, and if all of the omitted higher
  2198. parts were zero return zero, otherwise overflow occurred and
  2199. return one. */
  2200. int
  2201. APInt::tcMultiplyPart(integerPart *dst, const integerPart *src,
  2202. integerPart multiplier, integerPart carry,
  2203. unsigned int srcParts, unsigned int dstParts,
  2204. bool add)
  2205. {
  2206. unsigned int i, n;
  2207. /* Otherwise our writes of DST kill our later reads of SRC. */
  2208. assert(dst <= src || dst >= src + srcParts);
  2209. assert(dstParts <= srcParts + 1);
  2210. /* N loops; minimum of dstParts and srcParts. */
  2211. n = dstParts < srcParts ? dstParts: srcParts;
  2212. for (i = 0; i < n; i++) {
  2213. integerPart low, mid, high, srcPart;
  2214. /* [ LOW, HIGH ] = MULTIPLIER * SRC[i] + DST[i] + CARRY.
  2215. This cannot overflow, because
  2216. (n - 1) * (n - 1) + 2 (n - 1) = (n - 1) * (n + 1)
  2217. which is less than n^2. */
  2218. srcPart = src[i];
  2219. if (multiplier == 0 || srcPart == 0) {
  2220. low = carry;
  2221. high = 0;
  2222. } else {
  2223. low = lowHalf(srcPart) * lowHalf(multiplier);
  2224. high = highHalf(srcPart) * highHalf(multiplier);
  2225. mid = lowHalf(srcPart) * highHalf(multiplier);
  2226. high += highHalf(mid);
  2227. mid <<= integerPartWidth / 2;
  2228. if (low + mid < low)
  2229. high++;
  2230. low += mid;
  2231. mid = highHalf(srcPart) * lowHalf(multiplier);
  2232. high += highHalf(mid);
  2233. mid <<= integerPartWidth / 2;
  2234. if (low + mid < low)
  2235. high++;
  2236. low += mid;
  2237. /* Now add carry. */
  2238. if (low + carry < low)
  2239. high++;
  2240. low += carry;
  2241. }
  2242. if (add) {
  2243. /* And now DST[i], and store the new low part there. */
  2244. if (low + dst[i] < low)
  2245. high++;
  2246. dst[i] += low;
  2247. } else
  2248. dst[i] = low;
  2249. carry = high;
  2250. }
  2251. if (i < dstParts) {
  2252. /* Full multiplication, there is no overflow. */
  2253. assert(i + 1 == dstParts);
  2254. dst[i] = carry;
  2255. return 0;
  2256. } else {
  2257. /* We overflowed if there is carry. */
  2258. if (carry)
  2259. return 1;
  2260. /* We would overflow if any significant unwritten parts would be
  2261. non-zero. This is true if any remaining src parts are non-zero
  2262. and the multiplier is non-zero. */
  2263. if (multiplier)
  2264. for (; i < srcParts; i++)
  2265. if (src[i])
  2266. return 1;
  2267. /* We fitted in the narrow destination. */
  2268. return 0;
  2269. }
  2270. }
  2271. /* DST = LHS * RHS, where DST has the same width as the operands and
  2272. is filled with the least significant parts of the result. Returns
  2273. one if overflow occurred, otherwise zero. DST must be disjoint
  2274. from both operands. */
  2275. int
  2276. APInt::tcMultiply(integerPart *dst, const integerPart *lhs,
  2277. const integerPart *rhs, unsigned int parts)
  2278. {
  2279. unsigned int i;
  2280. int overflow;
  2281. assert(dst != lhs && dst != rhs);
  2282. overflow = 0;
  2283. tcSet(dst, 0, parts);
  2284. for (i = 0; i < parts; i++)
  2285. overflow |= tcMultiplyPart(&dst[i], lhs, rhs[i], 0, parts,
  2286. parts - i, true);
  2287. return overflow;
  2288. }
  2289. /* DST = LHS * RHS, where DST has width the sum of the widths of the
  2290. operands. No overflow occurs. DST must be disjoint from both
  2291. operands. Returns the number of parts required to hold the
  2292. result. */
  2293. unsigned int
  2294. APInt::tcFullMultiply(integerPart *dst, const integerPart *lhs,
  2295. const integerPart *rhs, unsigned int lhsParts,
  2296. unsigned int rhsParts)
  2297. {
  2298. /* Put the narrower number on the LHS for less loops below. */
  2299. if (lhsParts > rhsParts) {
  2300. return tcFullMultiply (dst, rhs, lhs, rhsParts, lhsParts);
  2301. } else {
  2302. unsigned int n;
  2303. assert(dst != lhs && dst != rhs);
  2304. tcSet(dst, 0, rhsParts);
  2305. for (n = 0; n < lhsParts; n++)
  2306. tcMultiplyPart(&dst[n], rhs, lhs[n], 0, rhsParts, rhsParts + 1, true);
  2307. n = lhsParts + rhsParts;
  2308. return n - (dst[n - 1] == 0);
  2309. }
  2310. }
  2311. /* If RHS is zero LHS and REMAINDER are left unchanged, return one.
  2312. Otherwise set LHS to LHS / RHS with the fractional part discarded,
  2313. set REMAINDER to the remainder, return zero. i.e.
  2314. OLD_LHS = RHS * LHS + REMAINDER
  2315. SCRATCH is a bignum of the same size as the operands and result for
  2316. use by the routine; its contents need not be initialized and are
  2317. destroyed. LHS, REMAINDER and SCRATCH must be distinct.
  2318. */
  2319. int
  2320. APInt::tcDivide(integerPart *lhs, const integerPart *rhs,
  2321. integerPart *remainder, integerPart *srhs,
  2322. unsigned int parts)
  2323. {
  2324. unsigned int n, shiftCount;
  2325. integerPart mask;
  2326. assert(lhs != remainder && lhs != srhs && remainder != srhs);
  2327. shiftCount = tcMSB(rhs, parts) + 1;
  2328. if (shiftCount == 0)
  2329. return true;
  2330. shiftCount = parts * integerPartWidth - shiftCount;
  2331. n = shiftCount / integerPartWidth;
  2332. mask = (integerPart) 1 << (shiftCount % integerPartWidth);
  2333. tcAssign(srhs, rhs, parts);
  2334. tcShiftLeft(srhs, parts, shiftCount);
  2335. tcAssign(remainder, lhs, parts);
  2336. tcSet(lhs, 0, parts);
  2337. /* Loop, subtracting SRHS if REMAINDER is greater and adding that to
  2338. the total. */
  2339. for (;;) {
  2340. int compare;
  2341. compare = tcCompare(remainder, srhs, parts);
  2342. if (compare >= 0) {
  2343. tcSubtract(remainder, srhs, 0, parts);
  2344. lhs[n] |= mask;
  2345. }
  2346. if (shiftCount == 0)
  2347. break;
  2348. shiftCount--;
  2349. tcShiftRight(srhs, parts, 1);
  2350. if ((mask >>= 1) == 0)
  2351. mask = (integerPart) 1 << (integerPartWidth - 1), n--;
  2352. }
  2353. return false;
  2354. }
  2355. /* Shift a bignum left COUNT bits in-place. Shifted in bits are zero.
  2356. There are no restrictions on COUNT. */
  2357. void
  2358. APInt::tcShiftLeft(integerPart *dst, unsigned int parts, unsigned int count)
  2359. {
  2360. if (count) {
  2361. unsigned int jump, shift;
  2362. /* Jump is the inter-part jump; shift is is intra-part shift. */
  2363. jump = count / integerPartWidth;
  2364. shift = count % integerPartWidth;
  2365. while (parts > jump) {
  2366. integerPart part;
  2367. parts--;
  2368. /* dst[i] comes from the two parts src[i - jump] and, if we have
  2369. an intra-part shift, src[i - jump - 1]. */
  2370. part = dst[parts - jump];
  2371. if (shift) {
  2372. part <<= shift;
  2373. if (parts >= jump + 1)
  2374. part |= dst[parts - jump - 1] >> (integerPartWidth - shift);
  2375. }
  2376. dst[parts] = part;
  2377. }
  2378. while (parts > 0)
  2379. dst[--parts] = 0;
  2380. }
  2381. }
  2382. /* Shift a bignum right COUNT bits in-place. Shifted in bits are
  2383. zero. There are no restrictions on COUNT. */
  2384. void
  2385. APInt::tcShiftRight(integerPart *dst, unsigned int parts, unsigned int count)
  2386. {
  2387. if (count) {
  2388. unsigned int i, jump, shift;
  2389. /* Jump is the inter-part jump; shift is is intra-part shift. */
  2390. jump = count / integerPartWidth;
  2391. shift = count % integerPartWidth;
  2392. /* Perform the shift. This leaves the most significant COUNT bits
  2393. of the result at zero. */
  2394. for (i = 0; i < parts; i++) {
  2395. integerPart part;
  2396. if (i + jump >= parts) {
  2397. part = 0;
  2398. } else {
  2399. part = dst[i + jump];
  2400. if (shift) {
  2401. part >>= shift;
  2402. if (i + jump + 1 < parts)
  2403. part |= dst[i + jump + 1] << (integerPartWidth - shift);
  2404. }
  2405. }
  2406. dst[i] = part;
  2407. }
  2408. }
  2409. }
  2410. /* Bitwise and of two bignums. */
  2411. void
  2412. APInt::tcAnd(integerPart *dst, const integerPart *rhs, unsigned int parts)
  2413. {
  2414. unsigned int i;
  2415. for (i = 0; i < parts; i++)
  2416. dst[i] &= rhs[i];
  2417. }
  2418. /* Bitwise inclusive or of two bignums. */
  2419. void
  2420. APInt::tcOr(integerPart *dst, const integerPart *rhs, unsigned int parts)
  2421. {
  2422. unsigned int i;
  2423. for (i = 0; i < parts; i++)
  2424. dst[i] |= rhs[i];
  2425. }
  2426. /* Bitwise exclusive or of two bignums. */
  2427. void
  2428. APInt::tcXor(integerPart *dst, const integerPart *rhs, unsigned int parts)
  2429. {
  2430. unsigned int i;
  2431. for (i = 0; i < parts; i++)
  2432. dst[i] ^= rhs[i];
  2433. }
  2434. /* Complement a bignum in-place. */
  2435. void
  2436. APInt::tcComplement(integerPart *dst, unsigned int parts)
  2437. {
  2438. unsigned int i;
  2439. for (i = 0; i < parts; i++)
  2440. dst[i] = ~dst[i];
  2441. }
  2442. /* Comparison (unsigned) of two bignums. */
  2443. int
  2444. APInt::tcCompare(const integerPart *lhs, const integerPart *rhs,
  2445. unsigned int parts)
  2446. {
  2447. while (parts) {
  2448. parts--;
  2449. if (lhs[parts] == rhs[parts])
  2450. continue;
  2451. if (lhs[parts] > rhs[parts])
  2452. return 1;
  2453. else
  2454. return -1;
  2455. }
  2456. return 0;
  2457. }
  2458. /* Increment a bignum in-place, return the carry flag. */
  2459. integerPart
  2460. APInt::tcIncrement(integerPart *dst, unsigned int parts)
  2461. {
  2462. unsigned int i;
  2463. for (i = 0; i < parts; i++)
  2464. if (++dst[i] != 0)
  2465. break;
  2466. return i == parts;
  2467. }
  2468. /* Decrement a bignum in-place, return the borrow flag. */
  2469. integerPart
  2470. APInt::tcDecrement(integerPart *dst, unsigned int parts) {
  2471. for (unsigned int i = 0; i < parts; i++) {
  2472. // If the current word is non-zero, then the decrement has no effect on the
  2473. // higher-order words of the integer and no borrow can occur. Exit early.
  2474. if (dst[i]--)
  2475. return 0;
  2476. }
  2477. // If every word was zero, then there is a borrow.
  2478. return 1;
  2479. }
  2480. /* Set the least significant BITS bits of a bignum, clear the
  2481. rest. */
  2482. void
  2483. APInt::tcSetLeastSignificantBits(integerPart *dst, unsigned int parts,
  2484. unsigned int bits)
  2485. {
  2486. unsigned int i;
  2487. i = 0;
  2488. while (bits > integerPartWidth) {
  2489. dst[i++] = ~(integerPart) 0;
  2490. bits -= integerPartWidth;
  2491. }
  2492. if (bits)
  2493. dst[i++] = ~(integerPart) 0 >> (integerPartWidth - bits);
  2494. while (i < parts)
  2495. dst[i++] = 0;
  2496. }