Skip to content

Commit

Permalink
[APInt] Assert correct values in APInt constructor
Browse files Browse the repository at this point in the history
If the uint64_t constructor is used, assert that the value is
actuall a signed or unsigned N-bit integer depending on whether
the isSigned flag is set.

Currently, we allow values to be silently truncated, which is
a constant source of subtle bugs -- a particularly common mistake
is to create -1 values without setting the isSigned flag, which
will work fine for all common bit widths (<= 64-bit) and miscompile
for larger integers.
  • Loading branch information
nikic committed Feb 1, 2024
1 parent 62ae7d9 commit f56c096
Show file tree
Hide file tree
Showing 5 changed files with 24 additions and 12 deletions.
12 changes: 11 additions & 1 deletion llvm/include/llvm/ADT/APInt.h
Original file line number Diff line number Diff line change
Expand Up @@ -108,9 +108,19 @@ class [[nodiscard]] APInt {
/// \param isSigned how to treat signedness of val
APInt(unsigned numBits, uint64_t val, bool isSigned = false)
: BitWidth(numBits) {
if (BitWidth == 0) {
assert(val == 0 && "Value must be zero for 0-bit APInt");
} else if (isSigned) {
assert(llvm::isIntN(BitWidth, val) &&
"Value is not an N-bit signed value");
} else {
assert(llvm::isUIntN(BitWidth, val) &&
"Value is not an N-bit unsigned value");
}
if (isSingleWord()) {
U.VAL = val;
clearUnusedBits();
if (isSigned)
clearUnusedBits();
} else {
initSlowCase(val, isSigned);
}
Expand Down
6 changes: 3 additions & 3 deletions llvm/lib/Support/APInt.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ APInt& APInt::operator-=(uint64_t RHS) {
APInt APInt::operator*(const APInt& RHS) const {
assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
if (isSingleWord())
return APInt(BitWidth, U.VAL * RHS.U.VAL);
return APInt(BitWidth, (U.VAL * RHS.U.VAL) & maxUIntN(BitWidth));

APInt Result(getMemory(getNumWords()), getBitWidth());
tcMultiply(Result.U.pVal, U.pVal, RHS.U.pVal, getNumWords());
Expand Down Expand Up @@ -907,7 +907,7 @@ APInt APInt::trunc(unsigned width) const {
assert(width <= BitWidth && "Invalid APInt Truncate request");

if (width <= APINT_BITS_PER_WORD)
return APInt(width, getRawData()[0]);
return APInt(width, getRawData()[0] & maxUIntN(width));

if (width == BitWidth)
return *this;
Expand Down Expand Up @@ -955,7 +955,7 @@ APInt APInt::sext(unsigned Width) const {
assert(Width >= BitWidth && "Invalid APInt SignExtend request");

if (Width <= APINT_BITS_PER_WORD)
return APInt(Width, SignExtend64(U.VAL, BitWidth));
return APInt(Width, SignExtend64(U.VAL, BitWidth), /*isSigned*/ true);

if (Width == BitWidth)
return *this;
Expand Down
2 changes: 1 addition & 1 deletion llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -308,7 +308,7 @@ Instruction *InstCombinerImpl::foldCmpLoadFromIndexedGlobal(
DL.getTypeAllocSize(Init->getType()->getArrayElementType());
auto MaskIdx = [&](Value *Idx) {
if (!GEP->isInBounds() && llvm::countr_zero(ElementSize) != 0) {
Value *Mask = ConstantInt::get(Idx->getType(), -1);
Value *Mask = Constant::getAllOnesValue(Idx->getType());
Mask = Builder.CreateLShr(Mask, llvm::countr_zero(ElementSize));
Idx = Builder.CreateAnd(Idx, Mask);
}
Expand Down
8 changes: 4 additions & 4 deletions llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -665,11 +665,11 @@ static Value *foldSelectICmpLshrAshr(const ICmpInst *IC, Value *TrueVal,
Value *X, *Y;
unsigned Bitwidth = CmpRHS->getType()->getScalarSizeInBits();
if ((Pred != ICmpInst::ICMP_SGT ||
!match(CmpRHS,
m_SpecificInt_ICMP(ICmpInst::ICMP_SGE, APInt(Bitwidth, -1)))) &&
!match(CmpRHS, m_SpecificInt_ICMP(ICmpInst::ICMP_SGE,
APInt::getAllOnes(Bitwidth)))) &&
(Pred != ICmpInst::ICMP_SLT ||
!match(CmpRHS,
m_SpecificInt_ICMP(ICmpInst::ICMP_SGE, APInt(Bitwidth, 0)))))
!match(CmpRHS, m_SpecificInt_ICMP(ICmpInst::ICMP_SGE,
APInt::getZero(Bitwidth)))))
return nullptr;

// Canonicalize so that ashr is in FalseVal.
Expand Down
8 changes: 5 additions & 3 deletions llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -553,7 +553,8 @@ Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilderBase &B) {
// strcmp(x, y) -> cnst (if both x and y are constant strings)
if (HasStr1 && HasStr2)
return ConstantInt::get(CI->getType(),
std::clamp(Str1.compare(Str2), -1, 1));
std::clamp(Str1.compare(Str2), -1, 1),
/*isSigned*/ true);

if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
return B.CreateNeg(B.CreateZExt(
Expand Down Expand Up @@ -638,7 +639,8 @@ Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilderBase &B) {
StringRef SubStr1 = substr(Str1, Length);
StringRef SubStr2 = substr(Str2, Length);
return ConstantInt::get(CI->getType(),
std::clamp(SubStr1.compare(SubStr2), -1, 1));
std::clamp(SubStr1.compare(SubStr2), -1, 1),
/*isSigned*/ true);
}

if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
Expand Down Expand Up @@ -1518,7 +1520,7 @@ static Value *optimizeMemCmpVarSize(CallInst *CI, Value *LHS, Value *RHS,
int IRes = UChar(LStr[Pos]) < UChar(RStr[Pos]) ? -1 : 1;
Value *MaxSize = ConstantInt::get(Size->getType(), Pos);
Value *Cmp = B.CreateICmp(ICmpInst::ICMP_ULE, Size, MaxSize);
Value *Res = ConstantInt::get(CI->getType(), IRes);
Value *Res = ConstantInt::get(CI->getType(), IRes, /*isSigned*/ true);
return B.CreateSelect(Cmp, Zero, Res);
}

Expand Down

0 comments on commit f56c096

Please sign in to comment.