diff options
author | Nikita Popov <npopov@redhat.com> | 2025-03-11 09:02:34 +0100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2025-03-11 09:02:34 +0100 |
commit | 8758e5fe47b5cf2d39d94ee6dc8834755c7687d9 (patch) | |
tree | 5814112b977e6f4bf73a188d50e9524c02bc965d /llvm/lib/Analysis/ConstantFolding.cpp | |
parent | 4a4444c0b2f68bec1db8e2cc8d133982d5a339e3 (diff) | |
download | llvm-8758e5fe47b5cf2d39d94ee6dc8834755c7687d9.zip llvm-8758e5fe47b5cf2d39d94ee6dc8834755c7687d9.tar.gz llvm-8758e5fe47b5cf2d39d94ee6dc8834755c7687d9.tar.bz2 |
[ConstantFolding] Fix handling of index width != pointer width (#130608)
Per LangRef:
> The offsets are then added to the low bits of the base address up to
the index type width, with silently-wrapping two’s complement
arithmetic. If the pointer size is larger than the index size, this
means that the bits outside the index type width will not be affected.
The transform as implemented was doubly wrong, because it just truncated
the original base pointer to the index width, losing the top bits
entirely. Make sure we preserve the bits and use wrapping arithmetic
within the low bits.
Diffstat (limited to 'llvm/lib/Analysis/ConstantFolding.cpp')
-rw-r--r-- | llvm/lib/Analysis/ConstantFolding.cpp | 9 |
1 files changed, 6 insertions, 3 deletions
diff --git a/llvm/lib/Analysis/ConstantFolding.cpp b/llvm/lib/Analysis/ConstantFolding.cpp index d645bf8..b0ba25c 100644 --- a/llvm/lib/Analysis/ConstantFolding.cpp +++ b/llvm/lib/Analysis/ConstantFolding.cpp @@ -943,18 +943,21 @@ Constant *SymbolicallyEvaluateGEP(const GEPOperator *GEP, // If the base value for this address is a literal integer value, fold the // getelementptr to the resulting integer value casted to the pointer type. - APInt BasePtr(BitWidth, 0); + APInt BasePtr(DL.getPointerTypeSizeInBits(Ptr->getType()), 0); if (auto *CE = dyn_cast<ConstantExpr>(Ptr)) { if (CE->getOpcode() == Instruction::IntToPtr) { if (auto *Base = dyn_cast<ConstantInt>(CE->getOperand(0))) - BasePtr = Base->getValue().zextOrTrunc(BitWidth); + BasePtr = Base->getValue().zextOrTrunc(BasePtr.getBitWidth()); } } auto *PTy = cast<PointerType>(Ptr->getType()); if ((Ptr->isNullValue() || BasePtr != 0) && !DL.isNonIntegralPointerType(PTy)) { - Constant *C = ConstantInt::get(Ptr->getContext(), Offset + BasePtr); + // If the index size is smaller than the pointer size, add to the low + // bits only. + BasePtr.insertBits(BasePtr.trunc(BitWidth) + Offset, 0); + Constant *C = ConstantInt::get(Ptr->getContext(), BasePtr); return ConstantExpr::getIntToPtr(C, ResTy); } |