APInt.cpp revision 385f7547b9755997b8bd918c2a4e2fc39d7d0207
1//===-- APInt.cpp - Implement APInt class ---------------------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file was developed by Sheng Zhou and is distributed under the 6// University of Illinois Open Source License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements a class to represent arbitrary precision integral 11// constant values. 12// 13//===----------------------------------------------------------------------===// 14 15#include "llvm/ADT/APInt.h" 16#include "llvm/DerivedTypes.h" 17#include "llvm/Support/MathExtras.h" 18#include <cstring> 19#include <cstdlib> 20#ifndef NDEBUG 21#include <iostream> 22#include <iomanip> 23#endif 24 25using namespace llvm; 26 27// A utility function for allocating memory, checking for allocation failures, 28// and ensuring the contents is zeroed. 29inline static uint64_t* getClearedMemory(uint32_t numWords) { 30 uint64_t * result = new uint64_t[numWords]; 31 assert(result && "APInt memory allocation fails!"); 32 memset(result, 0, numWords * sizeof(uint64_t)); 33 return result; 34} 35 36// A utility function for allocating memory and checking for allocation failure. 37inline static uint64_t* getMemory(uint32_t numWords) { 38 uint64_t * result = new uint64_t[numWords]; 39 assert(result && "APInt memory allocation fails!"); 40 return result; 41} 42 43APInt::APInt(uint32_t numBits, uint64_t val) 44 : BitWidth(numBits), VAL(0) { 45 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small"); 46 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large"); 47 if (isSingleWord()) 48 VAL = val & (~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - BitWidth)); 49 else { 50 pVal = getClearedMemory(getNumWords()); 51 pVal[0] = val; 52 } 53} 54 55APInt::APInt(uint32_t numBits, uint32_t numWords, uint64_t bigVal[]) 56 : BitWidth(numBits), VAL(0) { 57 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small"); 58 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large"); 59 assert(bigVal && "Null pointer detected!"); 60 if (isSingleWord()) 61 VAL = bigVal[0] & (~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - BitWidth)); 62 else { 63 pVal = getMemory(getNumWords()); 64 // Calculate the actual length of bigVal[]. 65 uint32_t maxN = std::max<uint32_t>(numWords, getNumWords()); 66 uint32_t minN = std::min<uint32_t>(numWords, getNumWords()); 67 memcpy(pVal, bigVal, (minN - 1) * APINT_WORD_SIZE); 68 pVal[minN-1] = bigVal[minN-1] & 69 (~uint64_t(0ULL) >> 70 (APINT_BITS_PER_WORD - BitWidth % APINT_BITS_PER_WORD)); 71 if (maxN == getNumWords()) 72 memset(pVal+numWords, 0, (getNumWords() - numWords) * APINT_WORD_SIZE); 73 } 74} 75 76/// @brief Create a new APInt by translating the char array represented 77/// integer value. 78APInt::APInt(uint32_t numbits, const char StrStart[], uint32_t slen, 79 uint8_t radix) 80 : BitWidth(numbits), VAL(0) { 81 fromString(numbits, StrStart, slen, radix); 82} 83 84/// @brief Create a new APInt by translating the string represented 85/// integer value. 86APInt::APInt(uint32_t numbits, const std::string& Val, uint8_t radix) 87 : BitWidth(numbits), VAL(0) { 88 assert(!Val.empty() && "String empty?"); 89 fromString(numbits, Val.c_str(), Val.size(), radix); 90} 91 92/// @brief Copy constructor 93APInt::APInt(const APInt& that) 94 : BitWidth(that.BitWidth), VAL(0) { 95 if (isSingleWord()) 96 VAL = that.VAL; 97 else { 98 pVal = getMemory(getNumWords()); 99 memcpy(pVal, that.pVal, getNumWords() * APINT_WORD_SIZE); 100 } 101} 102 103APInt::~APInt() { 104 if (!isSingleWord() && pVal) 105 delete[] pVal; 106} 107 108/// @brief Copy assignment operator. Create a new object from the given 109/// APInt one by initialization. 110APInt& APInt::operator=(const APInt& RHS) { 111 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same"); 112 if (isSingleWord()) 113 VAL = RHS.VAL; 114 else 115 memcpy(pVal, RHS.pVal, getNumWords() * APINT_WORD_SIZE); 116 return *this; 117} 118 119/// @brief Assignment operator. Assigns a common case integer value to 120/// the APInt. 121APInt& APInt::operator=(uint64_t RHS) { 122 if (isSingleWord()) 123 VAL = RHS; 124 else { 125 pVal[0] = RHS; 126 memset(pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE); 127 } 128 return *this; 129} 130 131/// add_1 - This function adds a single "digit" integer, y, to the multiple 132/// "digit" integer array, x[]. x[] is modified to reflect the addition and 133/// 1 is returned if there is a carry out, otherwise 0 is returned. 134/// @returns the carry of the addition. 135static uint64_t add_1(uint64_t dest[], 136 uint64_t x[], uint32_t len, 137 uint64_t y) { 138 for (uint32_t i = 0; i < len; ++i) { 139 dest[i] = y + x[i]; 140 if (dest[i] < y) 141 y = 1; 142 else { 143 y = 0; 144 break; 145 } 146 } 147 return y; 148} 149 150/// @brief Prefix increment operator. Increments the APInt by one. 151APInt& APInt::operator++() { 152 if (isSingleWord()) 153 ++VAL; 154 else 155 add_1(pVal, pVal, getNumWords(), 1); 156 clearUnusedBits(); 157 return *this; 158} 159 160/// sub_1 - This function subtracts a single "digit" (64-bit word), y, from 161/// the multi-digit integer array, x[], propagating the borrowed 1 value until 162/// no further borrowing is neeeded or it runs out of "digits" in x. The result 163/// is 1 if "borrowing" exhausted the digits in x, or 0 if x was not exhausted. 164/// In other words, if y > x then this function returns 1, otherwise 0. 165static uint64_t sub_1(uint64_t x[], uint32_t len, 166 uint64_t y) { 167 for (uint32_t i = 0; i < len; ++i) { 168 uint64_t X = x[i]; 169 x[i] -= y; 170 if (y > X) 171 y = 1; // We have to "borrow 1" from next "digit" 172 else { 173 y = 0; // No need to borrow 174 break; // Remaining digits are unchanged so exit early 175 } 176 } 177 return y; 178} 179 180/// @brief Prefix decrement operator. Decrements the APInt by one. 181APInt& APInt::operator--() { 182 if (isSingleWord()) 183 --VAL; 184 else 185 sub_1(pVal, getNumWords(), 1); 186 clearUnusedBits(); 187 return *this; 188} 189 190/// add - This function adds the integer array x[] by integer array 191/// y[] and returns the carry. 192static uint64_t add(uint64_t dest[], uint64_t x[], uint64_t y[], uint32_t len) { 193 uint64_t carry = 0; 194 for (uint32_t i = 0; i< len; ++i) { 195 uint64_t save = std::max(x[i],y[i]); 196 dest[i] = x[i] + y[i] + carry; 197 carry = dest[i] < save ? 1 : 0; 198 } 199 return carry; 200} 201 202/// @brief Addition assignment operator. Adds this APInt by the given APInt& 203/// RHS and assigns the result to this APInt. 204APInt& APInt::operator+=(const APInt& RHS) { 205 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same"); 206 if (isSingleWord()) 207 VAL += RHS.VAL; 208 else { 209 add(pVal, pVal, RHS.pVal, getNumWords()); 210 } 211 clearUnusedBits(); 212 return *this; 213} 214 215/// sub - This function subtracts the integer array x[] by 216/// integer array y[], and returns the borrow-out carry. 217static uint64_t sub(uint64_t *dest, const uint64_t *x, const uint64_t *y, 218 uint32_t len) { 219 bool borrow = false; 220 for (uint32_t i = 0; i < len; ++i) { 221 uint64_t x_tmp = borrow ? x[i] - 1 : x[i]; 222 borrow = y[i] > x_tmp || (borrow && x[i] == 0); 223 dest[i] = x_tmp - y[i]; 224 } 225 return borrow; 226} 227 228/// @brief Subtraction assignment operator. Subtracts this APInt by the given 229/// APInt &RHS and assigns the result to this APInt. 230APInt& APInt::operator-=(const APInt& RHS) { 231 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same"); 232 if (isSingleWord()) 233 VAL -= RHS.VAL; 234 else 235 sub(pVal, pVal, RHS.pVal, getNumWords()); 236 clearUnusedBits(); 237 return *this; 238} 239 240/// mul_1 - This function performs the multiplication operation on a 241/// large integer (represented as an integer array) and a uint64_t integer. 242/// @returns the carry of the multiplication. 243static uint64_t mul_1(uint64_t dest[], 244 uint64_t x[], uint32_t len, 245 uint64_t y) { 246 // Split y into high 32-bit part and low 32-bit part. 247 uint64_t ly = y & 0xffffffffULL, hy = y >> 32; 248 uint64_t carry = 0, lx, hx; 249 for (uint32_t i = 0; i < len; ++i) { 250 lx = x[i] & 0xffffffffULL; 251 hx = x[i] >> 32; 252 // hasCarry - A flag to indicate if has carry. 253 // hasCarry == 0, no carry 254 // hasCarry == 1, has carry 255 // hasCarry == 2, no carry and the calculation result == 0. 256 uint8_t hasCarry = 0; 257 dest[i] = carry + lx * ly; 258 // Determine if the add above introduces carry. 259 hasCarry = (dest[i] < carry) ? 1 : 0; 260 carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0); 261 // The upper limit of carry can be (2^32 - 1)(2^32 - 1) + 262 // (2^32 - 1) + 2^32 = 2^64. 263 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0); 264 265 carry += (lx * hy) & 0xffffffffULL; 266 dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL); 267 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) + 268 (carry >> 32) + ((lx * hy) >> 32) + hx * hy; 269 } 270 271 return carry; 272} 273 274/// mul - This function multiplies integer array x[] by integer array y[] and 275/// stores the result into integer array dest[]. 276/// Note the array dest[]'s size should no less than xlen + ylen. 277static void mul(uint64_t dest[], uint64_t x[], uint32_t xlen, 278 uint64_t y[], uint32_t ylen) { 279 dest[xlen] = mul_1(dest, x, xlen, y[0]); 280 281 for (uint32_t i = 1; i < ylen; ++i) { 282 uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32; 283 uint64_t carry = 0, lx, hx; 284 for (uint32_t j = 0; j < xlen; ++j) { 285 lx = x[j] & 0xffffffffULL; 286 hx = x[j] >> 32; 287 // hasCarry - A flag to indicate if has carry. 288 // hasCarry == 0, no carry 289 // hasCarry == 1, has carry 290 // hasCarry == 2, no carry and the calculation result == 0. 291 uint8_t hasCarry = 0; 292 uint64_t resul = carry + lx * ly; 293 hasCarry = (resul < carry) ? 1 : 0; 294 carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32); 295 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0); 296 297 carry += (lx * hy) & 0xffffffffULL; 298 resul = (carry << 32) | (resul & 0xffffffffULL); 299 dest[i+j] += resul; 300 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+ 301 (carry >> 32) + (dest[i+j] < resul ? 1 : 0) + 302 ((lx * hy) >> 32) + hx * hy; 303 } 304 dest[i+xlen] = carry; 305 } 306} 307 308/// @brief Multiplication assignment operator. Multiplies this APInt by the 309/// given APInt& RHS and assigns the result to this APInt. 310APInt& APInt::operator*=(const APInt& RHS) { 311 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same"); 312 if (isSingleWord()) 313 VAL *= RHS.VAL; 314 else { 315 // one-based first non-zero bit position. 316 uint32_t first = getActiveBits(); 317 uint32_t xlen = !first ? 0 : whichWord(first - 1) + 1; 318 if (!xlen) 319 return *this; 320 else { 321 first = RHS.getActiveBits(); 322 uint32_t ylen = !first ? 0 : whichWord(first - 1) + 1; 323 if (!ylen) { 324 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE); 325 return *this; 326 } 327 uint64_t *dest = getMemory(xlen+ylen); 328 mul(dest, pVal, xlen, RHS.pVal, ylen); 329 memcpy(pVal, dest, ((xlen + ylen >= getNumWords()) ? 330 getNumWords() : xlen + ylen) * APINT_WORD_SIZE); 331 delete[] dest; 332 } 333 } 334 clearUnusedBits(); 335 return *this; 336} 337 338/// @brief Bitwise AND assignment operator. Performs bitwise AND operation on 339/// this APInt and the given APInt& RHS, assigns the result to this APInt. 340APInt& APInt::operator&=(const APInt& RHS) { 341 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same"); 342 if (isSingleWord()) { 343 VAL &= RHS.VAL; 344 return *this; 345 } 346 uint32_t numWords = getNumWords(); 347 for (uint32_t i = 0; i < numWords; ++i) 348 pVal[i] &= RHS.pVal[i]; 349 return *this; 350} 351 352/// @brief Bitwise OR assignment operator. Performs bitwise OR operation on 353/// this APInt and the given APInt& RHS, assigns the result to this APInt. 354APInt& APInt::operator|=(const APInt& RHS) { 355 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same"); 356 if (isSingleWord()) { 357 VAL |= RHS.VAL; 358 return *this; 359 } 360 uint32_t numWords = getNumWords(); 361 for (uint32_t i = 0; i < numWords; ++i) 362 pVal[i] |= RHS.pVal[i]; 363 return *this; 364} 365 366/// @brief Bitwise XOR assignment operator. Performs bitwise XOR operation on 367/// this APInt and the given APInt& RHS, assigns the result to this APInt. 368APInt& APInt::operator^=(const APInt& RHS) { 369 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same"); 370 if (isSingleWord()) { 371 VAL ^= RHS.VAL; 372 this->clearUnusedBits(); 373 return *this; 374 } 375 uint32_t numWords = getNumWords(); 376 for (uint32_t i = 0; i < numWords; ++i) 377 pVal[i] ^= RHS.pVal[i]; 378 this->clearUnusedBits(); 379 return *this; 380} 381 382/// @brief Bitwise AND operator. Performs bitwise AND operation on this APInt 383/// and the given APInt& RHS. 384APInt APInt::operator&(const APInt& RHS) const { 385 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same"); 386 if (isSingleWord()) 387 return APInt(getBitWidth(), VAL & RHS.VAL); 388 389 APInt Result(*this); 390 uint32_t numWords = getNumWords(); 391 for (uint32_t i = 0; i < numWords; ++i) 392 Result.pVal[i] &= RHS.pVal[i]; 393 return Result; 394} 395 396/// @brief Bitwise OR operator. Performs bitwise OR operation on this APInt 397/// and the given APInt& RHS. 398APInt APInt::operator|(const APInt& RHS) const { 399 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same"); 400 if (isSingleWord()) 401 return APInt(getBitWidth(), VAL | RHS.VAL); 402 403 APInt Result(*this); 404 uint32_t numWords = getNumWords(); 405 for (uint32_t i = 0; i < numWords; ++i) 406 Result.pVal[i] |= RHS.pVal[i]; 407 return Result; 408} 409 410/// @brief Bitwise XOR operator. Performs bitwise XOR operation on this APInt 411/// and the given APInt& RHS. 412APInt APInt::operator^(const APInt& RHS) const { 413 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same"); 414 if (isSingleWord()) { 415 APInt Result(BitWidth, VAL ^ RHS.VAL); 416 Result.clearUnusedBits(); 417 return Result; 418 } 419 APInt Result(*this); 420 uint32_t numWords = getNumWords(); 421 for (uint32_t i = 0; i < numWords; ++i) 422 Result.pVal[i] ^= RHS.pVal[i]; 423 return Result; 424} 425 426/// @brief Logical negation operator. Performs logical negation operation on 427/// this APInt. 428bool APInt::operator !() const { 429 if (isSingleWord()) 430 return !VAL; 431 432 for (uint32_t i = 0; i < getNumWords(); ++i) 433 if (pVal[i]) 434 return false; 435 return true; 436} 437 438/// @brief Multiplication operator. Multiplies this APInt by the given APInt& 439/// RHS. 440APInt APInt::operator*(const APInt& RHS) const { 441 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same"); 442 if (isSingleWord()) { 443 APInt Result(BitWidth, VAL * RHS.VAL); 444 Result.clearUnusedBits(); 445 return Result; 446 } 447 APInt Result(*this); 448 Result *= RHS; 449 Result.clearUnusedBits(); 450 return Result; 451} 452 453/// @brief Addition operator. Adds this APInt by the given APInt& RHS. 454APInt APInt::operator+(const APInt& RHS) const { 455 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same"); 456 if (isSingleWord()) { 457 APInt Result(BitWidth, VAL + RHS.VAL); 458 Result.clearUnusedBits(); 459 return Result; 460 } 461 APInt Result(BitWidth, 0); 462 add(Result.pVal, this->pVal, RHS.pVal, getNumWords()); 463 Result.clearUnusedBits(); 464 return Result; 465} 466 467/// @brief Subtraction operator. Subtracts this APInt by the given APInt& RHS 468APInt APInt::operator-(const APInt& RHS) const { 469 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same"); 470 if (isSingleWord()) { 471 APInt Result(BitWidth, VAL - RHS.VAL); 472 Result.clearUnusedBits(); 473 return Result; 474 } 475 APInt Result(BitWidth, 0); 476 sub(Result.pVal, this->pVal, RHS.pVal, getNumWords()); 477 Result.clearUnusedBits(); 478 return Result; 479} 480 481/// @brief Array-indexing support. 482bool APInt::operator[](uint32_t bitPosition) const { 483 return (maskBit(bitPosition) & (isSingleWord() ? 484 VAL : pVal[whichWord(bitPosition)])) != 0; 485} 486 487/// @brief Equality operator. Compare this APInt with the given APInt& RHS 488/// for the validity of the equality relationship. 489bool APInt::operator==(const APInt& RHS) const { 490 if (isSingleWord()) 491 return VAL == RHS.VAL; 492 493 uint32_t n1 = getActiveBits(); 494 uint32_t n2 = RHS.getActiveBits(); 495 if (n1 != n2) 496 return false; 497 498 if (n1 <= APINT_BITS_PER_WORD) 499 return pVal[0] == RHS.pVal[0]; 500 501 for (int i = whichWord(n1 - 1); i >= 0; --i) 502 if (pVal[i] != RHS.pVal[i]) 503 return false; 504 return true; 505} 506 507/// @brief Equality operator. Compare this APInt with the given uint64_t value 508/// for the validity of the equality relationship. 509bool APInt::operator==(uint64_t Val) const { 510 if (isSingleWord()) 511 return VAL == Val; 512 513 uint32_t n = getActiveBits(); 514 if (n <= APINT_BITS_PER_WORD) 515 return pVal[0] == Val; 516 else 517 return false; 518} 519 520/// @brief Unsigned less than comparison 521bool APInt::ult(const APInt& RHS) const { 522 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison"); 523 if (isSingleWord()) 524 return VAL < RHS.VAL; 525 else { 526 uint32_t n1 = getActiveBits(); 527 uint32_t n2 = RHS.getActiveBits(); 528 if (n1 < n2) 529 return true; 530 else if (n2 < n1) 531 return false; 532 else if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD) 533 return pVal[0] < RHS.pVal[0]; 534 for (int i = whichWord(n1 - 1); i >= 0; --i) { 535 if (pVal[i] > RHS.pVal[i]) return false; 536 else if (pVal[i] < RHS.pVal[i]) return true; 537 } 538 } 539 return false; 540} 541 542/// @brief Signed less than comparison 543bool APInt::slt(const APInt& RHS) const { 544 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison"); 545 if (isSingleWord()) { 546 int64_t lhsSext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth); 547 int64_t rhsSext = (int64_t(RHS.VAL) << (64-BitWidth)) >> (64-BitWidth); 548 return lhsSext < rhsSext; 549 } 550 551 APInt lhs(*this); 552 APInt rhs(*this); 553 bool lhsNegative = false; 554 bool rhsNegative = false; 555 if (lhs[BitWidth-1]) { 556 lhsNegative = true; 557 lhs.flip(); 558 lhs++; 559 } 560 if (rhs[BitWidth-1]) { 561 rhsNegative = true; 562 rhs.flip(); 563 rhs++; 564 } 565 if (lhsNegative) 566 if (rhsNegative) 567 return !lhs.ult(rhs); 568 else 569 return true; 570 else if (rhsNegative) 571 return false; 572 else 573 return lhs.ult(rhs); 574} 575 576/// Set the given bit to 1 whose poition is given as "bitPosition". 577/// @brief Set a given bit to 1. 578APInt& APInt::set(uint32_t bitPosition) { 579 if (isSingleWord()) VAL |= maskBit(bitPosition); 580 else pVal[whichWord(bitPosition)] |= maskBit(bitPosition); 581 return *this; 582} 583 584/// @brief Set every bit to 1. 585APInt& APInt::set() { 586 if (isSingleWord()) 587 VAL = ~0ULL >> (APINT_BITS_PER_WORD - BitWidth); 588 else { 589 for (uint32_t i = 0; i < getNumWords() - 1; ++i) 590 pVal[i] = -1ULL; 591 pVal[getNumWords() - 1] = ~0ULL >> 592 (APINT_BITS_PER_WORD - BitWidth % APINT_BITS_PER_WORD); 593 } 594 return *this; 595} 596 597/// Set the given bit to 0 whose position is given as "bitPosition". 598/// @brief Set a given bit to 0. 599APInt& APInt::clear(uint32_t bitPosition) { 600 if (isSingleWord()) 601 VAL &= ~maskBit(bitPosition); 602 else 603 pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition); 604 return *this; 605} 606 607/// @brief Set every bit to 0. 608APInt& APInt::clear() { 609 if (isSingleWord()) 610 VAL = 0; 611 else 612 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE); 613 return *this; 614} 615 616/// @brief Bitwise NOT operator. Performs a bitwise logical NOT operation on 617/// this APInt. 618APInt APInt::operator~() const { 619 APInt API(*this); 620 API.flip(); 621 return API; 622} 623 624/// @brief Toggle every bit to its opposite value. 625APInt& APInt::flip() { 626 if (isSingleWord()) VAL = (~(VAL << 627 (APINT_BITS_PER_WORD - BitWidth))) >> (APINT_BITS_PER_WORD - BitWidth); 628 else { 629 uint32_t i = 0; 630 for (; i < getNumWords() - 1; ++i) 631 pVal[i] = ~pVal[i]; 632 uint32_t offset = 633 APINT_BITS_PER_WORD - (BitWidth - APINT_BITS_PER_WORD * (i - 1)); 634 pVal[i] = (~(pVal[i] << offset)) >> offset; 635 } 636 return *this; 637} 638 639/// Toggle a given bit to its opposite value whose position is given 640/// as "bitPosition". 641/// @brief Toggles a given bit to its opposite value. 642APInt& APInt::flip(uint32_t bitPosition) { 643 assert(bitPosition < BitWidth && "Out of the bit-width range!"); 644 if ((*this)[bitPosition]) clear(bitPosition); 645 else set(bitPosition); 646 return *this; 647} 648 649/// getMaxValue - This function returns the largest value 650/// for an APInt of the specified bit-width and if isSign == true, 651/// it should be largest signed value, otherwise unsigned value. 652APInt APInt::getMaxValue(uint32_t numBits, bool isSign) { 653 APInt Result(numBits, 0); 654 Result.set(); 655 if (isSign) 656 Result.clear(numBits - 1); 657 return Result; 658} 659 660/// getMinValue - This function returns the smallest value for 661/// an APInt of the given bit-width and if isSign == true, 662/// it should be smallest signed value, otherwise zero. 663APInt APInt::getMinValue(uint32_t numBits, bool isSign) { 664 APInt Result(numBits, 0); 665 if (isSign) 666 Result.set(numBits - 1); 667 return Result; 668} 669 670/// getAllOnesValue - This function returns an all-ones value for 671/// an APInt of the specified bit-width. 672APInt APInt::getAllOnesValue(uint32_t numBits) { 673 return getMaxValue(numBits, false); 674} 675 676/// getNullValue - This function creates an '0' value for an 677/// APInt of the specified bit-width. 678APInt APInt::getNullValue(uint32_t numBits) { 679 return getMinValue(numBits, false); 680} 681 682/// HiBits - This function returns the high "numBits" bits of this APInt. 683APInt APInt::getHiBits(uint32_t numBits) const { 684 return APIntOps::lshr(*this, BitWidth - numBits); 685} 686 687/// LoBits - This function returns the low "numBits" bits of this APInt. 688APInt APInt::getLoBits(uint32_t numBits) const { 689 return APIntOps::lshr(APIntOps::shl(*this, BitWidth - numBits), 690 BitWidth - numBits); 691} 692 693bool APInt::isPowerOf2() const { 694 return (!!*this) && !(*this & (*this - APInt(BitWidth,1))); 695} 696 697/// countLeadingZeros - This function is a APInt version corresponding to 698/// llvm/include/llvm/Support/MathExtras.h's function 699/// countLeadingZeros_{32, 64}. It performs platform optimal form of counting 700/// the number of zeros from the most significant bit to the first one bit. 701/// @returns numWord() * 64 if the value is zero. 702uint32_t APInt::countLeadingZeros() const { 703 uint32_t Count = 0; 704 if (isSingleWord()) 705 Count = CountLeadingZeros_64(VAL); 706 else { 707 for (uint32_t i = getNumWords(); i > 0u; --i) { 708 if (pVal[i-1] == 0) 709 Count += APINT_BITS_PER_WORD; 710 else { 711 Count += CountLeadingZeros_64(pVal[i-1]); 712 break; 713 } 714 } 715 } 716 return Count - (APINT_BITS_PER_WORD - (BitWidth % APINT_BITS_PER_WORD)); 717} 718 719/// countTrailingZeros - This function is a APInt version corresponding to 720/// llvm/include/llvm/Support/MathExtras.h's function 721/// countTrailingZeros_{32, 64}. It performs platform optimal form of counting 722/// the number of zeros from the least significant bit to the first one bit. 723/// @returns numWord() * 64 if the value is zero. 724uint32_t APInt::countTrailingZeros() const { 725 if (isSingleWord()) 726 return CountTrailingZeros_64(VAL); 727 APInt Tmp( ~(*this) & ((*this) - APInt(BitWidth,1)) ); 728 return getNumWords() * APINT_BITS_PER_WORD - Tmp.countLeadingZeros(); 729} 730 731/// countPopulation - This function is a APInt version corresponding to 732/// llvm/include/llvm/Support/MathExtras.h's function 733/// countPopulation_{32, 64}. It counts the number of set bits in a value. 734/// @returns 0 if the value is zero. 735uint32_t APInt::countPopulation() const { 736 if (isSingleWord()) 737 return CountPopulation_64(VAL); 738 uint32_t Count = 0; 739 for (uint32_t i = 0; i < getNumWords(); ++i) 740 Count += CountPopulation_64(pVal[i]); 741 return Count; 742} 743 744 745/// byteSwap - This function returns a byte-swapped representation of the 746/// this APInt. 747APInt APInt::byteSwap() const { 748 assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!"); 749 if (BitWidth == 16) 750 return APInt(BitWidth, ByteSwap_16(VAL)); 751 else if (BitWidth == 32) 752 return APInt(BitWidth, ByteSwap_32(VAL)); 753 else if (BitWidth == 48) { 754 uint64_t Tmp1 = ((VAL >> 32) << 16) | (VAL & 0xFFFF); 755 Tmp1 = ByteSwap_32(Tmp1); 756 uint64_t Tmp2 = (VAL >> 16) & 0xFFFF; 757 Tmp2 = ByteSwap_16(Tmp2); 758 return 759 APInt(BitWidth, 760 (Tmp1 & 0xff) | ((Tmp1<<16) & 0xffff00000000ULL) | (Tmp2 << 16)); 761 } else if (BitWidth == 64) 762 return APInt(BitWidth, ByteSwap_64(VAL)); 763 else { 764 APInt Result(BitWidth, 0); 765 char *pByte = (char*)Result.pVal; 766 for (uint32_t i = 0; i < BitWidth / APINT_WORD_SIZE / 2; ++i) { 767 char Tmp = pByte[i]; 768 pByte[i] = pByte[BitWidth / APINT_WORD_SIZE - 1 - i]; 769 pByte[BitWidth / APINT_WORD_SIZE - i - 1] = Tmp; 770 } 771 return Result; 772 } 773} 774 775/// GreatestCommonDivisor - This function returns the greatest common 776/// divisor of the two APInt values using Enclid's algorithm. 777APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1, 778 const APInt& API2) { 779 APInt A = API1, B = API2; 780 while (!!B) { 781 APInt T = B; 782 B = APIntOps::urem(A, B); 783 A = T; 784 } 785 return A; 786} 787 788/// DoubleRoundToAPInt - This function convert a double value to 789/// a APInt value. 790APInt llvm::APIntOps::RoundDoubleToAPInt(double Double) { 791 union { 792 double D; 793 uint64_t I; 794 } T; 795 T.D = Double; 796 bool isNeg = T.I >> 63; 797 int64_t exp = ((T.I >> 52) & 0x7ff) - 1023; 798 if (exp < 0) 799 return APInt(64ull, 0u); 800 uint64_t mantissa = ((T.I << 12) >> 12) | (1ULL << 52); 801 if (exp < 52) 802 return isNeg ? -APInt(64u, mantissa >> (52 - exp)) : 803 APInt(64u, mantissa >> (52 - exp)); 804 APInt Tmp(exp + 1, mantissa); 805 Tmp = Tmp.shl(exp - 52); 806 return isNeg ? -Tmp : Tmp; 807} 808 809/// RoundToDouble - This function convert this APInt to a double. 810/// The layout for double is as following (IEEE Standard 754): 811/// -------------------------------------- 812/// | Sign Exponent Fraction Bias | 813/// |-------------------------------------- | 814/// | 1[63] 11[62-52] 52[51-00] 1023 | 815/// -------------------------------------- 816double APInt::roundToDouble(bool isSigned) const { 817 818 // Handle the simple case where the value is contained in one uint64_t. 819 if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) { 820 if (isSigned) { 821 int64_t sext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth); 822 return double(sext); 823 } else 824 return double(VAL); 825 } 826 827 // Determine if the value is negative. 828 bool isNeg = isSigned ? (*this)[BitWidth-1] : false; 829 830 // Construct the absolute value if we're negative. 831 APInt Tmp(isNeg ? -(*this) : (*this)); 832 833 // Figure out how many bits we're using. 834 uint32_t n = Tmp.getActiveBits(); 835 836 // The exponent (without bias normalization) is just the number of bits 837 // we are using. Note that the sign bit is gone since we constructed the 838 // absolute value. 839 uint64_t exp = n; 840 841 // Return infinity for exponent overflow 842 if (exp > 1023) { 843 if (!isSigned || !isNeg) 844 return double(1.0E300 * 1.0E300); // positive infinity 845 else 846 return double(-1.0E300 * 1.0E300); // negative infinity 847 } 848 exp += 1023; // Increment for 1023 bias 849 850 // Number of bits in mantissa is 52. To obtain the mantissa value, we must 851 // extract the high 52 bits from the correct words in pVal. 852 uint64_t mantissa; 853 unsigned hiWord = whichWord(n-1); 854 if (hiWord == 0) { 855 mantissa = Tmp.pVal[0]; 856 if (n > 52) 857 mantissa >>= n - 52; // shift down, we want the top 52 bits. 858 } else { 859 assert(hiWord > 0 && "huh?"); 860 uint64_t hibits = Tmp.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD); 861 uint64_t lobits = Tmp.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD); 862 mantissa = hibits | lobits; 863 } 864 865 // The leading bit of mantissa is implicit, so get rid of it. 866 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0; 867 union { 868 double D; 869 uint64_t I; 870 } T; 871 T.I = sign | (exp << 52) | mantissa; 872 return T.D; 873} 874 875// Truncate to new width. 876void APInt::trunc(uint32_t width) { 877 assert(width < BitWidth && "Invalid APInt Truncate request"); 878} 879 880// Sign extend to a new width. 881void APInt::sext(uint32_t width) { 882 assert(width > BitWidth && "Invalid APInt SignExtend request"); 883} 884 885// Zero extend to a new width. 886void APInt::zext(uint32_t width) { 887 assert(width > BitWidth && "Invalid APInt ZeroExtend request"); 888} 889 890/// Arithmetic right-shift this APInt by shiftAmt. 891/// @brief Arithmetic right-shift function. 892APInt APInt::ashr(uint32_t shiftAmt) const { 893 APInt API(*this); 894 if (API.isSingleWord()) 895 API.VAL = 896 (((int64_t(API.VAL) << (APINT_BITS_PER_WORD - API.BitWidth)) >> 897 (APINT_BITS_PER_WORD - API.BitWidth)) >> shiftAmt) & 898 (~uint64_t(0UL) >> (APINT_BITS_PER_WORD - API.BitWidth)); 899 else { 900 if (shiftAmt >= API.BitWidth) { 901 memset(API.pVal, API[API.BitWidth-1] ? 1 : 0, 902 (API.getNumWords()-1) * APINT_WORD_SIZE); 903 API.pVal[API.getNumWords() - 1] = 904 ~uint64_t(0UL) >> 905 (APINT_BITS_PER_WORD - API.BitWidth % APINT_BITS_PER_WORD); 906 } else { 907 uint32_t i = 0; 908 for (; i < API.BitWidth - shiftAmt; ++i) 909 if (API[i+shiftAmt]) 910 API.set(i); 911 else 912 API.clear(i); 913 for (; i < API.BitWidth; ++i) 914 if (API[API.BitWidth-1]) 915 API.set(i); 916 else API.clear(i); 917 } 918 } 919 return API; 920} 921 922/// Logical right-shift this APInt by shiftAmt. 923/// @brief Logical right-shift function. 924APInt APInt::lshr(uint32_t shiftAmt) const { 925 APInt API(*this); 926 if (API.isSingleWord()) 927 API.VAL >>= shiftAmt; 928 else { 929 if (shiftAmt >= API.BitWidth) 930 memset(API.pVal, 0, API.getNumWords() * APINT_WORD_SIZE); 931 uint32_t i = 0; 932 for (i = 0; i < API.BitWidth - shiftAmt; ++i) 933 if (API[i+shiftAmt]) API.set(i); 934 else API.clear(i); 935 for (; i < API.BitWidth; ++i) 936 API.clear(i); 937 } 938 return API; 939} 940 941/// Left-shift this APInt by shiftAmt. 942/// @brief Left-shift function. 943APInt APInt::shl(uint32_t shiftAmt) const { 944 APInt API(*this); 945 if (API.isSingleWord()) 946 API.VAL <<= shiftAmt; 947 else if (shiftAmt >= API.BitWidth) 948 memset(API.pVal, 0, API.getNumWords() * APINT_WORD_SIZE); 949 else { 950 if (uint32_t offset = shiftAmt / APINT_BITS_PER_WORD) { 951 for (uint32_t i = API.getNumWords() - 1; i > offset - 1; --i) 952 API.pVal[i] = API.pVal[i-offset]; 953 memset(API.pVal, 0, offset * APINT_WORD_SIZE); 954 } 955 shiftAmt %= APINT_BITS_PER_WORD; 956 uint32_t i; 957 for (i = API.getNumWords() - 1; i > 0; --i) 958 API.pVal[i] = (API.pVal[i] << shiftAmt) | 959 (API.pVal[i-1] >> (APINT_BITS_PER_WORD - shiftAmt)); 960 API.pVal[i] <<= shiftAmt; 961 } 962 API.clearUnusedBits(); 963 return API; 964} 965 966#if 0 967/// subMul - This function substracts x[len-1:0] * y from 968/// dest[offset+len-1:offset], and returns the most significant 969/// word of the product, minus the borrow-out from the subtraction. 970static uint32_t subMul(uint32_t dest[], uint32_t offset, 971 uint32_t x[], uint32_t len, uint32_t y) { 972 uint64_t yl = (uint64_t) y & 0xffffffffL; 973 uint32_t carry = 0; 974 uint32_t j = 0; 975 do { 976 uint64_t prod = ((uint64_t) x[j] & 0xffffffffUL) * yl; 977 uint32_t prod_low = (uint32_t) prod; 978 uint32_t prod_high = (uint32_t) (prod >> 32); 979 prod_low += carry; 980 carry = (prod_low < carry ? 1 : 0) + prod_high; 981 uint32_t x_j = dest[offset+j]; 982 prod_low = x_j - prod_low; 983 if (prod_low > x_j) ++carry; 984 dest[offset+j] = prod_low; 985 } while (++j < len); 986 return carry; 987} 988 989/// unitDiv - This function divides N by D, 990/// and returns (remainder << 32) | quotient. 991/// Assumes (N >> 32) < D. 992static uint64_t unitDiv(uint64_t N, uint32_t D) { 993 uint64_t q, r; // q: quotient, r: remainder. 994 uint64_t a1 = N >> 32; // a1: high 32-bit part of N. 995 uint64_t a0 = N & 0xffffffffL; // a0: low 32-bit part of N 996 if (a1 < ((D - a1 - (a0 >> 31)) & 0xffffffffL)) { 997 q = N / D; 998 r = N % D; 999 } 1000 else { 1001 // Compute c1*2^32 + c0 = a1*2^32 + a0 - 2^31*d 1002 uint64_t c = N - ((uint64_t) D << 31); 1003 // Divide (c1*2^32 + c0) by d 1004 q = c / D; 1005 r = c % D; 1006 // Add 2^31 to quotient 1007 q += 1 << 31; 1008 } 1009 1010 return (r << 32) | (q & 0xFFFFFFFFl); 1011} 1012 1013#endif 1014 1015/// div - This is basically Knuth's formulation of the classical algorithm. 1016/// Correspondance with Knuth's notation: 1017/// Knuth's u[0:m+n] == zds[nx:0]. 1018/// Knuth's v[1:n] == y[ny-1:0] 1019/// Knuth's n == ny. 1020/// Knuth's m == nx-ny. 1021/// Our nx == Knuth's m+n. 1022/// Could be re-implemented using gmp's mpn_divrem: 1023/// zds[nx] = mpn_divrem (&zds[ny], 0, zds, nx, y, ny). 1024 1025/// Implementation of Knuth's Algorithm D (Division of nonnegative integers) 1026/// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The 1027/// variables here have the same names as in the algorithm. Comments explain 1028/// the algorithm and any deviation from it. 1029static void KnuthDiv(uint32_t *u, uint32_t *v, uint32_t *q, uint32_t* r, 1030 uint32_t m, uint32_t n) { 1031 assert(u && "Must provide dividend"); 1032 assert(v && "Must provide divisor"); 1033 assert(q && "Must provide quotient"); 1034 assert(n>1 && "n must be > 1"); 1035 1036 // Knuth uses the value b as the base of the number system. In our case b 1037 // is 2^31 so we just set it to -1u. 1038 uint64_t b = uint64_t(1) << 32; 1039 1040 // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of 1041 // u and v by d. Note that we have taken Knuth's advice here to use a power 1042 // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of 1043 // 2 allows us to shift instead of multiply and it is easy to determine the 1044 // shift amount from the leading zeros. We are basically normalizing the u 1045 // and v so that its high bits are shifted to the top of v's range without 1046 // overflow. Note that this can require an extra word in u so that u must 1047 // be of length m+n+1. 1048 uint32_t shift = CountLeadingZeros_32(v[n-1]); 1049 uint32_t v_carry = 0; 1050 uint32_t u_carry = 0; 1051 if (shift) { 1052 for (uint32_t i = 0; i < m+n; ++i) { 1053 uint32_t u_tmp = u[i] >> (32 - shift); 1054 u[i] = (u[i] << shift) | u_carry; 1055 u_carry = u_tmp; 1056 } 1057 for (uint32_t i = 0; i < n; ++i) { 1058 uint32_t v_tmp = v[i] >> (32 - shift); 1059 v[i] = (v[i] << shift) | v_carry; 1060 v_carry = v_tmp; 1061 } 1062 } 1063 u[m+n] = u_carry; 1064 1065 // D2. [Initialize j.] Set j to m. This is the loop counter over the places. 1066 int j = m; 1067 do { 1068 // D3. [Calculate q'.]. 1069 // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q') 1070 // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r') 1071 // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease 1072 // qp by 1, inrease rp by v[n-1], and repeat this test if rp < b. The test 1073 // on v[n-2] determines at high speed most of the cases in which the trial 1074 // value qp is one too large, and it eliminates all cases where qp is two 1075 // too large. 1076 uint64_t qp = ((uint64_t(u[j+n]) << 32) | uint64_t(u[j+n-1])) / v[n-1]; 1077 uint64_t rp = ((uint64_t(u[j+n]) << 32) | uint64_t(u[j+n-1])) % v[n-1]; 1078 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) { 1079 qp--; 1080 rp += v[n-1]; 1081 } 1082 if (rp < b) 1083 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) { 1084 qp--; 1085 rp += v[n-1]; 1086 } 1087 1088 // D4. [Multiply and subtract.] Replace u with u - q*v (for each word). 1089 uint32_t borrow = 0; 1090 for (uint32_t i = 0; i < n; i++) { 1091 uint32_t save = u[j+i]; 1092 u[j+i] = uint64_t(u[j+i]) - (qp * v[i]) - borrow; 1093 if (u[j+i] > save) { 1094 borrow = 1; 1095 u[j+i+1] += b; 1096 } else { 1097 borrow = 0; 1098 } 1099 } 1100 if (borrow) 1101 u[j+n] += 1; 1102 1103 // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was 1104 // negative, go to step D6; otherwise go on to step D7. 1105 q[j] = qp; 1106 if (borrow) { 1107 // D6. [Add back]. The probability that this step is necessary is very 1108 // small, on the order of only 2/b. Make sure that test data accounts for 1109 // this possibility. Decreate qj by 1 and add v[...] to u[...]. A carry 1110 // will occur to the left of u[j+n], and it should be ignored since it 1111 // cancels with the borrow that occurred in D4. 1112 uint32_t carry = 0; 1113 for (uint32_t i = 0; i < n; i++) { 1114 uint32_t save = u[j+i]; 1115 u[j+i] += v[i] + carry; 1116 carry = u[j+i] < save; 1117 } 1118 } 1119 1120 // D7. [Loop on j.] Decreate j by one. Now if j >= 0, go back to D3. 1121 j--; 1122 } while (j >= 0); 1123 1124 // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired 1125 // remainder may be obtained by dividing u[...] by d. If r is non-null we 1126 // compute the remainder (urem uses this). 1127 if (r) { 1128 // The value d is expressed by the "shift" value above since we avoided 1129 // multiplication by d by using a shift left. So, all we have to do is 1130 // shift right here. In order to mak 1131 uint32_t mask = ~0u >> (32 - shift); 1132 uint32_t carry = 0; 1133 for (int i = n-1; i >= 0; i--) { 1134 uint32_t save = u[i] & mask; 1135 r[i] = (u[i] >> shift) | carry; 1136 carry = save; 1137 } 1138 } 1139} 1140 1141// This function makes calling KnuthDiv a little more convenient. It uses 1142// APInt parameters instead of uint32_t* parameters. It can also divide APInt 1143// values of different widths. 1144void APInt::divide(const APInt LHS, uint32_t lhsWords, 1145 const APInt &RHS, uint32_t rhsWords, 1146 APInt *Quotient, APInt *Remainder) 1147{ 1148 assert(lhsWords >= rhsWords && "Fractional result"); 1149 1150 // First, compose the values into an array of 32-bit words instead of 1151 // 64-bit words. This is a necessity of both the "short division" algorithm 1152 // and the the Knuth "classical algorithm" which requires there to be native 1153 // operations for +, -, and * on an m bit value with an m*2 bit result. We 1154 // can't use 64-bit operands here because we don't have native results of 1155 // 128-bits. Furthremore, casting the 64-bit values to 32-bit values won't 1156 // work on large-endian machines. 1157 uint64_t mask = ~0ull >> (sizeof(uint32_t)*8); 1158 uint32_t n = rhsWords * 2; 1159 uint32_t m = (lhsWords * 2) - n; 1160 // FIXME: allocate space on stack if m and n are sufficiently small. 1161 uint32_t *U = new uint32_t[m + n + 1]; 1162 memset(U, 0, (m+n+1)*sizeof(uint32_t)); 1163 for (unsigned i = 0; i < lhsWords; ++i) { 1164 uint64_t tmp = (lhsWords == 1 ? LHS.VAL : LHS.pVal[i]); 1165 U[i * 2] = tmp & mask; 1166 U[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8); 1167 } 1168 U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm. 1169 1170 uint32_t *V = new uint32_t[n]; 1171 memset(V, 0, (n)*sizeof(uint32_t)); 1172 for (unsigned i = 0; i < rhsWords; ++i) { 1173 uint64_t tmp = (rhsWords == 1 ? RHS.VAL : RHS.pVal[i]); 1174 V[i * 2] = tmp & mask; 1175 V[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8); 1176 } 1177 1178 // Set up the quotient and remainder 1179 uint32_t *Q = new uint32_t[m+n]; 1180 memset(Q, 0, (m+n) * sizeof(uint32_t)); 1181 uint32_t *R = 0; 1182 if (Remainder) { 1183 R = new uint32_t[n]; 1184 memset(R, 0, n * sizeof(uint32_t)); 1185 } 1186 1187 // Now, adjust m and n for the Knuth division. n is the number of words in 1188 // the divisor. m is the number of words by which the dividend exceeds the 1189 // divisor (i.e. m+n is the length of the dividend). These sizes must not 1190 // contain any zero words or the Knuth algorithm fails. 1191 for (unsigned i = n; i > 0 && V[i-1] == 0; i--) { 1192 n--; 1193 m++; 1194 } 1195 for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--) 1196 m--; 1197 1198 // If we're left with only a single word for the divisor, Knuth doesn't work 1199 // so we implement the short division algorithm here. This is much simpler 1200 // and faster because we are certain that we can divide a 64-bit quantity 1201 // by a 32-bit quantity at hardware speed and short division is simply a 1202 // series of such operations. This is just like doing short division but we 1203 // are using base 2^32 instead of base 10. 1204 assert(n != 0 && "Divide by zero?"); 1205 if (n == 1) { 1206 uint32_t divisor = V[0]; 1207 uint32_t remainder = 0; 1208 for (int i = m+n-1; i >= 0; i--) { 1209 uint64_t partial_dividend = uint64_t(remainder) << 32 | U[i]; 1210 if (partial_dividend == 0) { 1211 Q[i] = 0; 1212 remainder = 0; 1213 } else if (partial_dividend < divisor) { 1214 Q[i] = 0; 1215 remainder = partial_dividend; 1216 } else if (partial_dividend == divisor) { 1217 Q[i] = 1; 1218 remainder = 0; 1219 } else { 1220 Q[i] = partial_dividend / divisor; 1221 remainder = partial_dividend - (Q[i] * divisor); 1222 } 1223 } 1224 if (R) 1225 R[0] = remainder; 1226 } else { 1227 // Now we're ready to invoke the Knuth classical divide algorithm. In this 1228 // case n > 1. 1229 KnuthDiv(U, V, Q, R, m, n); 1230 } 1231 1232 // If the caller wants the quotient 1233 if (Quotient) { 1234 // Set up the Quotient value's memory. 1235 if (Quotient->BitWidth != LHS.BitWidth) { 1236 if (Quotient->isSingleWord()) 1237 Quotient->VAL = 0; 1238 else 1239 delete Quotient->pVal; 1240 Quotient->BitWidth = LHS.BitWidth; 1241 if (!Quotient->isSingleWord()) 1242 Quotient->pVal = getClearedMemory(lhsWords); 1243 } else 1244 Quotient->clear(); 1245 1246 // The quotient is in Q. Reconstitute the quotient into Quotient's low 1247 // order words. 1248 if (lhsWords == 1) { 1249 uint64_t tmp = 1250 uint64_t(Q[0]) | (uint64_t(Q[1]) << (APINT_BITS_PER_WORD / 2)); 1251 if (Quotient->isSingleWord()) 1252 Quotient->VAL = tmp; 1253 else 1254 Quotient->pVal[0] = tmp; 1255 } else { 1256 assert(!Quotient->isSingleWord() && "Quotient APInt not large enough"); 1257 for (unsigned i = 0; i < lhsWords; ++i) 1258 Quotient->pVal[i] = 1259 uint64_t(Q[i*2]) | (uint64_t(Q[i*2+1]) << (APINT_BITS_PER_WORD / 2)); 1260 } 1261 } 1262 1263 // If the caller wants the remainder 1264 if (Remainder) { 1265 // Set up the Remainder value's memory. 1266 if (Remainder->BitWidth != RHS.BitWidth) { 1267 if (Remainder->isSingleWord()) 1268 Remainder->VAL = 0; 1269 else 1270 delete Remainder->pVal; 1271 Remainder->BitWidth = RHS.BitWidth; 1272 if (!Remainder->isSingleWord()) 1273 Remainder->pVal = getClearedMemory(rhsWords); 1274 } else 1275 Remainder->clear(); 1276 1277 // The remainder is in R. Reconstitute the remainder into Remainder's low 1278 // order words. 1279 if (rhsWords == 1) { 1280 uint64_t tmp = 1281 uint64_t(R[0]) | (uint64_t(R[1]) << (APINT_BITS_PER_WORD / 2)); 1282 if (Remainder->isSingleWord()) 1283 Remainder->VAL = tmp; 1284 else 1285 Remainder->pVal[0] = tmp; 1286 } else { 1287 assert(!Remainder->isSingleWord() && "Remainder APInt not large enough"); 1288 for (unsigned i = 0; i < rhsWords; ++i) 1289 Remainder->pVal[i] = 1290 uint64_t(R[i*2]) | (uint64_t(R[i*2+1]) << (APINT_BITS_PER_WORD / 2)); 1291 } 1292 } 1293 1294 // Clean up the memory we allocated. 1295 delete [] U; 1296 delete [] V; 1297 delete [] Q; 1298 delete [] R; 1299} 1300 1301/// Unsigned divide this APInt by APInt RHS. 1302/// @brief Unsigned division function for APInt. 1303APInt APInt::udiv(const APInt& RHS) const { 1304 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same"); 1305 1306 // First, deal with the easy case 1307 if (isSingleWord()) { 1308 assert(RHS.VAL != 0 && "Divide by zero?"); 1309 return APInt(BitWidth, VAL / RHS.VAL); 1310 } 1311 1312 // Get some facts about the LHS and RHS number of bits and words 1313 uint32_t rhsBits = RHS.getActiveBits(); 1314 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1); 1315 assert(rhsWords && "Divided by zero???"); 1316 uint32_t lhsBits = this->getActiveBits(); 1317 uint32_t lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1); 1318 1319 // Make a temporary to hold the result 1320 APInt Result(*this); 1321 1322 // Deal with some degenerate cases 1323 if (!lhsWords) 1324 return Result; // 0 / X == 0 1325 else if (lhsWords < rhsWords || Result.ult(RHS)) { 1326 // X / Y with X < Y == 0 1327 memset(Result.pVal, 0, Result.getNumWords() * APINT_WORD_SIZE); 1328 return Result; 1329 } else if (Result == RHS) { 1330 // X / X == 1 1331 memset(Result.pVal, 0, Result.getNumWords() * APINT_WORD_SIZE); 1332 Result.pVal[0] = 1; 1333 return Result; 1334 } else if (lhsWords == 1 && rhsWords == 1) { 1335 // All high words are zero, just use native divide 1336 Result.pVal[0] /= RHS.pVal[0]; 1337 return Result; 1338 } 1339 1340 // We have to compute it the hard way. Invoke the Knuth divide algorithm. 1341 APInt Quotient(1,0); // to hold result. 1342 divide(*this, lhsWords, RHS, rhsWords, &Quotient, 0); 1343 return Quotient; 1344} 1345 1346/// Unsigned remainder operation on APInt. 1347/// @brief Function for unsigned remainder operation. 1348APInt APInt::urem(const APInt& RHS) const { 1349 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same"); 1350 if (isSingleWord()) { 1351 assert(RHS.VAL != 0 && "Remainder by zero?"); 1352 return APInt(BitWidth, VAL % RHS.VAL); 1353 } 1354 1355 // Make a temporary to hold the result 1356 APInt Result(*this); 1357 1358 // Get some facts about the RHS 1359 uint32_t rhsBits = RHS.getActiveBits(); 1360 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1); 1361 assert(rhsWords && "Performing remainder operation by zero ???"); 1362 1363 // Get some facts about the LHS 1364 uint32_t lhsBits = Result.getActiveBits(); 1365 uint32_t lhsWords = !lhsBits ? 0 : (Result.whichWord(lhsBits - 1) + 1); 1366 1367 // Check the degenerate cases 1368 if (lhsWords == 0) { 1369 // 0 % Y == 0 1370 memset(Result.pVal, 0, Result.getNumWords() * APINT_WORD_SIZE); 1371 return Result; 1372 } else if (lhsWords < rhsWords || Result.ult(RHS)) { 1373 // X % Y == X iff X < Y 1374 return Result; 1375 } else if (Result == RHS) { 1376 // X % X == 0; 1377 memset(Result.pVal, 0, Result.getNumWords() * APINT_WORD_SIZE); 1378 return Result; 1379 } else if (lhsWords == 1) { 1380 // All high words are zero, just use native remainder 1381 Result.pVal[0] %= RHS.pVal[0]; 1382 return Result; 1383 } 1384 1385 // We have to compute it the hard way. Invoke the Knute divide algorithm. 1386 APInt Remainder(1,0); 1387 divide(*this, lhsWords, RHS, rhsWords, 0, &Remainder); 1388 return Remainder; 1389} 1390 1391/// @brief Converts a char array into an integer. 1392void APInt::fromString(uint32_t numbits, const char *str, uint32_t slen, 1393 uint8_t radix) { 1394 // Check our assumptions here 1395 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) && 1396 "Radix should be 2, 8, 10, or 16!"); 1397 assert(str && "String is null?"); 1398 assert(slen <= numbits || radix != 2 && "Insufficient bit width"); 1399 assert(slen*3 <= numbits || radix != 8 && "Insufficient bit width"); 1400 assert(slen*4 <= numbits || radix != 16 && "Insufficient bit width"); 1401 assert((slen*64)/20 <= numbits || radix != 10 && "Insufficient bit width"); 1402 1403 // Allocate memory 1404 if (!isSingleWord()) 1405 pVal = getClearedMemory(getNumWords()); 1406 1407 // Figure out if we can shift instead of multiply 1408 uint32_t shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0); 1409 1410 // Set up an APInt for the digit to add outside the loop so we don't 1411 // constantly construct/destruct it. 1412 APInt apdigit(getBitWidth(), 0); 1413 APInt apradix(getBitWidth(), radix); 1414 1415 // Enter digit traversal loop 1416 for (unsigned i = 0; i < slen; i++) { 1417 // Get a digit 1418 uint32_t digit = 0; 1419 char cdigit = str[i]; 1420 if (isdigit(cdigit)) 1421 digit = cdigit - '0'; 1422 else if (isxdigit(cdigit)) 1423 if (cdigit >= 'a') 1424 digit = cdigit - 'a' + 10; 1425 else if (cdigit >= 'A') 1426 digit = cdigit - 'A' + 10; 1427 else 1428 assert(0 && "huh?"); 1429 else 1430 assert(0 && "Invalid character in digit string"); 1431 1432 // Shift or multiple the value by the radix 1433 if (shift) 1434 this->shl(shift); 1435 else 1436 *this *= apradix; 1437 1438 // Add in the digit we just interpreted 1439 apdigit.pVal[0] = digit; 1440 *this += apdigit; 1441 } 1442} 1443 1444/// to_string - This function translates the APInt into a string. 1445std::string APInt::toString(uint8_t radix, bool wantSigned) const { 1446 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) && 1447 "Radix should be 2, 8, 10, or 16!"); 1448 static const char *digits[] = { 1449 "0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F" 1450 }; 1451 std::string result; 1452 uint32_t bits_used = getActiveBits(); 1453 if (isSingleWord()) { 1454 char buf[65]; 1455 const char *format = (radix == 10 ? (wantSigned ? "%lld" : "%llu") : 1456 (radix == 16 ? "%llX" : (radix == 8 ? "%llo" : 0))); 1457 if (format) { 1458 if (wantSigned) { 1459 int64_t sextVal = (int64_t(VAL) << (APINT_BITS_PER_WORD-BitWidth)) >> 1460 (APINT_BITS_PER_WORD-BitWidth); 1461 sprintf(buf, format, sextVal); 1462 } else 1463 sprintf(buf, format, VAL); 1464 } else { 1465 memset(buf, 0, 65); 1466 uint64_t v = VAL; 1467 while (bits_used) { 1468 uint32_t bit = v & 1; 1469 bits_used--; 1470 buf[bits_used] = digits[bit][0]; 1471 v >>=1; 1472 } 1473 } 1474 result = buf; 1475 return result; 1476 } 1477 1478 if (radix != 10) { 1479 uint64_t mask = radix - 1; 1480 uint32_t shift = (radix == 16 ? 4 : radix == 8 ? 3 : 1); 1481 uint32_t nibbles = APINT_BITS_PER_WORD / shift; 1482 for (uint32_t i = 0; i < getNumWords(); ++i) { 1483 uint64_t value = pVal[i]; 1484 for (uint32_t j = 0; j < nibbles; ++j) { 1485 result.insert(0, digits[ value & mask ]); 1486 value >>= shift; 1487 } 1488 } 1489 return result; 1490 } 1491 1492 APInt tmp(*this); 1493 APInt divisor(4, radix); 1494 APInt zero(tmp.getBitWidth(), 0); 1495 size_t insert_at = 0; 1496 if (wantSigned && tmp[BitWidth-1]) { 1497 // They want to print the signed version and it is a negative value 1498 // Flip the bits and add one to turn it into the equivalent positive 1499 // value and put a '-' in the result. 1500 tmp.flip(); 1501 tmp++; 1502 result = "-"; 1503 insert_at = 1; 1504 } 1505 if (tmp == APInt(tmp.getBitWidth(), 0)) 1506 result = "0"; 1507 else while (tmp.ne(zero)) { 1508 APInt APdigit(1,0); 1509 APInt tmp2(tmp.getBitWidth(), 0); 1510 divide(tmp, tmp.getNumWords(), divisor, divisor.getNumWords(), &tmp2, 1511 &APdigit); 1512 uint32_t digit = APdigit.getValue(); 1513 assert(digit < radix && "divide failed"); 1514 result.insert(insert_at,digits[digit]); 1515 tmp = tmp2; 1516 } 1517 1518 return result; 1519} 1520 1521#ifndef NDEBUG 1522void APInt::dump() const 1523{ 1524 std::cerr << "APInt(" << BitWidth << ")=" << std::setbase(16); 1525 if (isSingleWord()) 1526 std::cerr << VAL; 1527 else for (unsigned i = getNumWords(); i > 0; i--) { 1528 std::cerr << pVal[i-1] << " "; 1529 } 1530 std::cerr << " (" << this->toString(10, false) << ")\n" << std::setbase(10); 1531} 1532#endif 1533