//===-- APInt.cpp - Implement APInt class ---------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Sheng Zhou and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements a class to represent arbitrary precision integral
// constant values.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/APInt.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Support/MathExtras.h"
#include <cstring>
#include <cstdlib>
using namespace llvm;
/// mul_1 - This function performs the multiplication operation on a
/// large integer (represented as an integer array) and a uint64_t integer.
/// @returns the carry of the multiplication.
static uint64_t mul_1(uint64_t dest[], uint64_t x[],
unsigned len, uint64_t y) {
// Split y into high 32-bit part and low 32-bit part.
uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
uint64_t carry = 0, lx, hx;
for (unsigned i = 0; i < len; ++i) {
lx = x[i] & 0xffffffffULL;
hx = x[i] >> 32;
// hasCarry - A flag to indicate if has carry.
// hasCarry == 0, no carry
// hasCarry == 1, has carry
// hasCarry == 2, no carry and the calculation result == 0.
uint8_t hasCarry = 0;
dest[i] = carry + lx * ly;
// Determine if the add above introduces carry.
hasCarry = (dest[i] < carry) ? 1 : 0;
carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
// The upper limit of carry can be (2^32 - 1)(2^32 - 1) +
// (2^32 - 1) + 2^32 = 2^64.
hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
carry += (lx * hy) & 0xffffffffULL;
dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) +
(carry >> 32) + ((lx * hy) >> 32) + hx * hy;
}
return carry;
}
/// mul - This function multiplies integer array x[] by integer array y[] and
/// stores the result into integer array dest[].
/// Note the array dest[]'s size should no less than xlen + ylen.
static void mul(uint64_t dest[], uint64_t x[], unsigned xlen,
uint64_t y[], unsigned ylen) {
dest[xlen] = mul_1(dest, x, xlen, y[0]);
for (unsigned i = 1; i < ylen; ++i) {
uint64_t ly