APInt.cpp 81 KB

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