xref: /src/contrib/llvm-project/llvm/lib/Support/APSInt.cpp (revision 06c3fb2749bda94cb5201f81ffdb8fa6c3161b2e)
1009b1c42SEd Schouten //===-- llvm/ADT/APSInt.cpp - Arbitrary Precision Signed Int ---*- C++ -*--===//
2009b1c42SEd Schouten //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6009b1c42SEd Schouten //
7009b1c42SEd Schouten //===----------------------------------------------------------------------===//
8009b1c42SEd Schouten //
9009b1c42SEd Schouten // This file implements the APSInt class, which is a simple class that
10009b1c42SEd Schouten // represents an arbitrary sized integer that knows its signedness.
11009b1c42SEd Schouten //
12009b1c42SEd Schouten //===----------------------------------------------------------------------===//
13009b1c42SEd Schouten 
14009b1c42SEd Schouten #include "llvm/ADT/APSInt.h"
15009b1c42SEd Schouten #include "llvm/ADT/FoldingSet.h"
1601095a5dSDimitry Andric #include "llvm/ADT/StringRef.h"
17cfca06d7SDimitry Andric #include <cassert>
18009b1c42SEd Schouten 
19009b1c42SEd Schouten using namespace llvm;
20009b1c42SEd Schouten 
APSInt(StringRef Str)211a82d4c0SDimitry Andric APSInt::APSInt(StringRef Str) {
221a82d4c0SDimitry Andric   assert(!Str.empty() && "Invalid string length");
231a82d4c0SDimitry Andric 
241a82d4c0SDimitry Andric   // (Over-)estimate the required number of bits.
251a82d4c0SDimitry Andric   unsigned NumBits = ((Str.size() * 64) / 19) + 2;
26e6d15924SDimitry Andric   APInt Tmp(NumBits, Str, /*radix=*/10);
271a82d4c0SDimitry Andric   if (Str[0] == '-') {
287fa27ce4SDimitry Andric     unsigned MinBits = Tmp.getSignificantBits();
29cfca06d7SDimitry Andric     if (MinBits < NumBits)
30cfca06d7SDimitry Andric       Tmp = Tmp.trunc(std::max<unsigned>(1, MinBits));
31e6d15924SDimitry Andric     *this = APSInt(Tmp, /*isUnsigned=*/false);
321a82d4c0SDimitry Andric     return;
331a82d4c0SDimitry Andric   }
341a82d4c0SDimitry Andric   unsigned ActiveBits = Tmp.getActiveBits();
35cfca06d7SDimitry Andric   if (ActiveBits < NumBits)
36cfca06d7SDimitry Andric     Tmp = Tmp.trunc(std::max<unsigned>(1, ActiveBits));
37e6d15924SDimitry Andric   *this = APSInt(Tmp, /*isUnsigned=*/true);
381a82d4c0SDimitry Andric }
391a82d4c0SDimitry Andric 
Profile(FoldingSetNodeID & ID) const40009b1c42SEd Schouten void APSInt::Profile(FoldingSetNodeID& ID) const {
41009b1c42SEd Schouten   ID.AddInteger((unsigned) (IsUnsigned ? 1 : 0));
42009b1c42SEd Schouten   APInt::Profile(ID);
43009b1c42SEd Schouten }
44