Author: Nikita Popov
Date: 2025-10-14T12:44:14+02:00
New Revision: 6f514313263da0fb4b6793689f6849e0f8fdb18b
URL: https://github.com/llvm/llvm-project/commit/6f514313263da0fb4b6793689f6849e0f8fdb18b
DIFF: https://github.com/llvm/llvm-project/commit/6f514313263da0fb4b6793689f6849e0f8fdb18b.diff
LOG: [ConstantFold] Support ptrtoaddr in global alignment fold
Treat it the same way as ptrtoint.
Added:
Modified:
llvm/lib/IR/ConstantFold.cpp
llvm/unittests/IR/ConstantsTest.cpp
Removed:
################################################################################
diff --git a/llvm/lib/IR/ConstantFold.cpp b/llvm/lib/IR/ConstantFold.cpp
index 3842b1afab05d..6a9ef2efa321f 100644
--- a/llvm/lib/IR/ConstantFold.cpp
+++ b/llvm/lib/IR/ConstantFold.cpp
@@ -741,7 +741,8 @@ Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode, Constant *C1,
assert(!CI2->isZero() && "And zero handled above");
if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
// If and'ing the address of a global with a constant, fold it.
- if (CE1->getOpcode() == Instruction::PtrToInt &&
+ if ((CE1->getOpcode() == Instruction::PtrToInt ||
+ CE1->getOpcode() == Instruction::PtrToAddr) &&
isa<GlobalValue>(CE1->getOperand(0))) {
GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
diff --git a/llvm/unittests/IR/ConstantsTest.cpp b/llvm/unittests/IR/ConstantsTest.cpp
index 54c7ddd003fc6..6376165cbe766 100644
--- a/llvm/unittests/IR/ConstantsTest.cpp
+++ b/llvm/unittests/IR/ConstantsTest.cpp
@@ -564,13 +564,17 @@ TEST(ConstantsTest, FoldGlobalVariablePtr) {
Global->setAlignment(Align(4));
- ConstantInt *TheConstant(ConstantInt::get(IntType, 2));
+ ConstantInt *TheConstant = ConstantInt::get(IntType, 2);
- Constant *TheConstantExpr(ConstantExpr::getPtrToInt(Global.get(), IntType));
+ Constant *PtrToInt = ConstantExpr::getPtrToInt(Global.get(), IntType);
+ ASSERT_TRUE(
+ ConstantFoldBinaryInstruction(Instruction::And, PtrToInt, TheConstant)
+ ->isNullValue());
- ASSERT_TRUE(ConstantFoldBinaryInstruction(Instruction::And, TheConstantExpr,
- TheConstant)
- ->isNullValue());
+ Constant *PtrToAddr = ConstantExpr::getPtrToAddr(Global.get(), IntType);
+ ASSERT_TRUE(
+ ConstantFoldBinaryInstruction(Instruction::And, PtrToAddr, TheConstant)
+ ->isNullValue());
}
// Check that containsUndefOrPoisonElement and containsPoisonElement is working