Skip to content

Commit 506aaa1

Browse files
committed
[APInt] Assert correct values in APInt constructor
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.
1 parent 62ae7d9 commit 506aaa1

22 files changed

+346
-313
lines changed

llvm/include/llvm/ADT/APFixedPoint.h

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,9 @@ class APFixedPoint {
160160
}
161161

162162
APFixedPoint(uint64_t Val, const FixedPointSemantics &Sema)
163-
: APFixedPoint(APInt(Sema.getWidth(), Val, Sema.isSigned()), Sema) {}
163+
: APFixedPoint(APInt(Sema.getWidth(), Val, Sema.isSigned(),
164+
/*implicitTrunc*/ true),
165+
Sema) {}
164166

165167
// Zero initialization.
166168
APFixedPoint(const FixedPointSemantics &Sema) : APFixedPoint(0, Sema) {}

llvm/include/llvm/ADT/APInt.h

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -106,11 +106,26 @@ class [[nodiscard]] APInt {
106106
/// \param numBits the bit width of the constructed APInt
107107
/// \param val the initial value of the APInt
108108
/// \param isSigned how to treat signedness of val
109-
APInt(unsigned numBits, uint64_t val, bool isSigned = false)
109+
/// \param implicitTrunc allow implicit truncation of non-zero/sign bits of
110+
/// val beyond the range of numBits
111+
APInt(unsigned numBits, uint64_t val, bool isSigned = false,
112+
bool implicitTrunc = false)
110113
: BitWidth(numBits) {
114+
if (!implicitTrunc) {
115+
if (BitWidth == 0) {
116+
assert(val == 0 && "Value must be zero for 0-bit APInt");
117+
} else if (isSigned) {
118+
assert(llvm::isIntN(BitWidth, val) &&
119+
"Value is not an N-bit signed value");
120+
} else {
121+
assert(llvm::isUIntN(BitWidth, val) &&
122+
"Value is not an N-bit unsigned value");
123+
}
124+
}
111125
if (isSingleWord()) {
112126
U.VAL = val;
113-
clearUnusedBits();
127+
if (implicitTrunc || isSigned)
128+
clearUnusedBits();
114129
} else {
115130
initSlowCase(val, isSigned);
116131
}

llvm/lib/Analysis/ConstantFolding.cpp

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -889,7 +889,8 @@ Constant *SymbolicallyEvaluateGEP(const GEPOperator *GEP,
889889
APInt Offset = APInt(
890890
BitWidth,
891891
DL.getIndexedOffsetInType(
892-
SrcElemTy, ArrayRef((Value *const *)Ops.data() + 1, Ops.size() - 1)));
892+
SrcElemTy, ArrayRef((Value *const *)Ops.data() + 1, Ops.size() - 1)),
893+
/*isSigned*/ true, /*implicitTrunc*/ true);
893894

894895
// If this is a GEP of a GEP, fold it all into a single GEP.
895896
while (auto *GEP = dyn_cast<GEPOperator>(Ptr)) {
@@ -3322,8 +3323,9 @@ ConstantFoldScalarFrexpCall(Constant *Op, Type *IntTy) {
33223323

33233324
// The exponent is an "unspecified value" for inf/nan. We use zero to avoid
33243325
// using undef.
3325-
Constant *Result1 = FrexpMant.isFinite() ? ConstantInt::get(IntTy, FrexpExp)
3326-
: ConstantInt::getNullValue(IntTy);
3326+
Constant *Result1 = FrexpMant.isFinite()
3327+
? ConstantInt::getSigned(IntTy, FrexpExp)
3328+
: ConstantInt::getNullValue(IntTy);
33273329
return {Result0, Result1};
33283330
}
33293331

llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4542,7 +4542,7 @@ OpenMPIRBuilder::createTargetInit(const LocationDescription &Loc, bool IsSPMD,
45424542
Builder.CreateCall(Fn, {KernelEnvironment, KernelLaunchEnvironment});
45434543

45444544
Value *ExecUserCode = Builder.CreateICmpEQ(
4545-
ThreadKind, ConstantInt::get(ThreadKind->getType(), -1),
4545+
ThreadKind, Constant::getAllOnesValue(ThreadKind->getType()),
45464546
"exec_user_code");
45474547

45484548
// ThreadKind = __kmpc_target_init(...)

llvm/lib/FuzzMutate/OpDescriptor.cpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@ void fuzzerop::makeConstantsWithType(Type *T, std::vector<Constant *> &Cs) {
1717
uint64_t W = IntTy->getBitWidth();
1818
Cs.push_back(ConstantInt::get(IntTy, 0));
1919
Cs.push_back(ConstantInt::get(IntTy, 1));
20-
Cs.push_back(ConstantInt::get(IntTy, 42));
20+
Cs.push_back(ConstantInt::get(
21+
IntTy, APInt(W, 42, /*isSigned*/ false, /*implicitTrunc*/ true)));
2122
Cs.push_back(ConstantInt::get(IntTy, APInt::getMaxValue(W)));
2223
Cs.push_back(ConstantInt::get(IntTy, APInt::getMinValue(W)));
2324
Cs.push_back(ConstantInt::get(IntTy, APInt::getSignedMaxValue(W)));

llvm/lib/IR/ConstantRange.cpp

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1743,7 +1743,7 @@ ConstantRange ConstantRange::ctlz(bool ZeroIsPoison) const {
17431743
// Zero is either safe or not in the range. The output range is composed by
17441744
// the result of countLeadingZero of the two extremes.
17451745
return getNonEmpty(APInt(getBitWidth(), getUnsignedMax().countl_zero()),
1746-
APInt(getBitWidth(), getUnsignedMin().countl_zero() + 1));
1746+
APInt(getBitWidth(), getUnsignedMin().countl_zero()) + 1);
17471747
}
17481748

17491749
static ConstantRange getUnsignedCountTrailingZerosRange(const APInt &Lower,
@@ -1802,7 +1802,7 @@ ConstantRange ConstantRange::cttz(bool ZeroIsPoison) const {
18021802
}
18031803

18041804
if (isFullSet())
1805-
return getNonEmpty(Zero, APInt(BitWidth, BitWidth + 1));
1805+
return getNonEmpty(Zero, APInt(BitWidth, BitWidth) + 1);
18061806
if (!isWrappedSet())
18071807
return getUnsignedCountTrailingZerosRange(Lower, Upper);
18081808
// The range is wrapped. We decompose it into two ranges, [0, Upper) and
@@ -1847,7 +1847,7 @@ ConstantRange ConstantRange::ctpop() const {
18471847
unsigned BitWidth = getBitWidth();
18481848
APInt Zero = APInt::getZero(BitWidth);
18491849
if (isFullSet())
1850-
return getNonEmpty(Zero, APInt(BitWidth, BitWidth + 1));
1850+
return getNonEmpty(Zero, APInt(BitWidth, BitWidth) + 1);
18511851
if (!isWrappedSet())
18521852
return getUnsignedPopCountRange(Lower, Upper);
18531853
// The range is wrapped. We decompose it into two ranges, [0, Upper) and

llvm/lib/Support/APInt.cpp

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -234,7 +234,8 @@ APInt& APInt::operator-=(uint64_t RHS) {
234234
APInt APInt::operator*(const APInt& RHS) const {
235235
assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
236236
if (isSingleWord())
237-
return APInt(BitWidth, U.VAL * RHS.U.VAL);
237+
return APInt(BitWidth, U.VAL * RHS.U.VAL, /*isSigned*/ false,
238+
/*implicitTrunc*/ true);
238239

239240
APInt Result(getMemory(getNumWords()), getBitWidth());
240241
tcMultiply(Result.U.pVal, U.pVal, RHS.U.pVal, getNumWords());
@@ -455,15 +456,17 @@ APInt APInt::extractBits(unsigned numBits, unsigned bitPosition) const {
455456
"Illegal bit extraction");
456457

457458
if (isSingleWord())
458-
return APInt(numBits, U.VAL >> bitPosition);
459+
return APInt(numBits, U.VAL >> bitPosition, /*isSigned*/ false,
460+
/*implicitTrunc*/ true);
459461

460462
unsigned loBit = whichBit(bitPosition);
461463
unsigned loWord = whichWord(bitPosition);
462464
unsigned hiWord = whichWord(bitPosition + numBits - 1);
463465

464466
// Single word result extracting bits from a single word source.
465467
if (loWord == hiWord)
466-
return APInt(numBits, U.pVal[loWord] >> loBit);
468+
return APInt(numBits, U.pVal[loWord] >> loBit, /*isSigned*/ false,
469+
/*implicitTrunc*/ true);
467470

468471
// Extracting bits that start on a source word boundary can be done
469472
// as a fast memory copy.
@@ -907,7 +910,8 @@ APInt APInt::trunc(unsigned width) const {
907910
assert(width <= BitWidth && "Invalid APInt Truncate request");
908911

909912
if (width <= APINT_BITS_PER_WORD)
910-
return APInt(width, getRawData()[0]);
913+
return APInt(width, getRawData()[0], /*isSigned*/ false,
914+
/*implicitTrunc*/ true);
911915

912916
if (width == BitWidth)
913917
return *this;
@@ -955,7 +959,7 @@ APInt APInt::sext(unsigned Width) const {
955959
assert(Width >= BitWidth && "Invalid APInt SignExtend request");
956960

957961
if (Width <= APINT_BITS_PER_WORD)
958-
return APInt(Width, SignExtend64(U.VAL, BitWidth));
962+
return APInt(Width, SignExtend64(U.VAL, BitWidth), /*isSigned*/ true);
959963

960964
if (Width == BitWidth)
961965
return *this;

llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -308,7 +308,7 @@ Instruction *InstCombinerImpl::foldCmpLoadFromIndexedGlobal(
308308
DL.getTypeAllocSize(Init->getType()->getArrayElementType());
309309
auto MaskIdx = [&](Value *Idx) {
310310
if (!GEP->isInBounds() && llvm::countr_zero(ElementSize) != 0) {
311-
Value *Mask = ConstantInt::get(Idx->getType(), -1);
311+
Value *Mask = Constant::getAllOnesValue(Idx->getType());
312312
Mask = Builder.CreateLShr(Mask, llvm::countr_zero(ElementSize));
313313
Idx = Builder.CreateAnd(Idx, Mask);
314314
}

llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -665,11 +665,11 @@ static Value *foldSelectICmpLshrAshr(const ICmpInst *IC, Value *TrueVal,
665665
Value *X, *Y;
666666
unsigned Bitwidth = CmpRHS->getType()->getScalarSizeInBits();
667667
if ((Pred != ICmpInst::ICMP_SGT ||
668-
!match(CmpRHS,
669-
m_SpecificInt_ICMP(ICmpInst::ICMP_SGE, APInt(Bitwidth, -1)))) &&
668+
!match(CmpRHS, m_SpecificInt_ICMP(ICmpInst::ICMP_SGE,
669+
APInt::getAllOnes(Bitwidth)))) &&
670670
(Pred != ICmpInst::ICMP_SLT ||
671-
!match(CmpRHS,
672-
m_SpecificInt_ICMP(ICmpInst::ICMP_SGE, APInt(Bitwidth, 0)))))
671+
!match(CmpRHS, m_SpecificInt_ICMP(ICmpInst::ICMP_SGE,
672+
APInt::getZero(Bitwidth)))))
673673
return nullptr;
674674

675675
// Canonicalize so that ashr is in FalseVal.

llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -224,7 +224,7 @@ static Value *convertStrToInt(CallInst *CI, StringRef &Str, Value *EndPtr,
224224
// Unsigned negation doesn't overflow.
225225
Result = -Result;
226226

227-
return ConstantInt::get(RetTy, Result);
227+
return ConstantInt::get(RetTy, Result, AsSigned);
228228
}
229229

230230
static bool isOnlyUsedInComparisonWithZero(Value *V) {
@@ -553,7 +553,8 @@ Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilderBase &B) {
553553
// strcmp(x, y) -> cnst (if both x and y are constant strings)
554554
if (HasStr1 && HasStr2)
555555
return ConstantInt::get(CI->getType(),
556-
std::clamp(Str1.compare(Str2), -1, 1));
556+
std::clamp(Str1.compare(Str2), -1, 1),
557+
/*isSigned*/ true);
557558

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

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

llvm/unittests/ADT/APFixedPointTest.cpp

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -240,27 +240,28 @@ void CheckIntPart(const FixedPointSemantics &Sema, int64_t IntPart) {
240240
APFixedPoint ValWithFract(
241241
APInt(Sema.getWidth(),
242242
relativeShr(IntPart, Sema.getLsbWeight()) + FullFactPart,
243-
Sema.isSigned()),
243+
Sema.isSigned(), /*implicitTrunc*/ true),
244244
Sema);
245245
ASSERT_EQ(ValWithFract.getIntPart(), IntPart);
246246

247247
// Just fraction
248-
APFixedPoint JustFract(APInt(Sema.getWidth(), FullFactPart, Sema.isSigned()),
248+
APFixedPoint JustFract(APInt(Sema.getWidth(), FullFactPart, Sema.isSigned(),
249+
/*implicitTrunc*/ true),
249250
Sema);
250251
ASSERT_EQ(JustFract.getIntPart(), 0);
251252

252253
// Whole number
253254
APFixedPoint WholeNum(APInt(Sema.getWidth(),
254255
relativeShr(IntPart, Sema.getLsbWeight()),
255-
Sema.isSigned()),
256+
Sema.isSigned(), /*implicitTrunc*/ true),
256257
Sema);
257258
ASSERT_EQ(WholeNum.getIntPart(), IntPart);
258259

259260
// Negative
260261
if (Sema.isSigned()) {
261262
APFixedPoint Negative(APInt(Sema.getWidth(),
262263
relativeShr(IntPart, Sema.getLsbWeight()),
263-
Sema.isSigned()),
264+
Sema.isSigned(), /*implicitTrunc*/ true),
264265
Sema);
265266
ASSERT_EQ(Negative.getIntPart(), IntPart);
266267
}

0 commit comments

Comments
 (0)