APInt.cpp 86 KB

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