Skip to content

Avoid undefined behavior in shift operators during constant folding of DIExpressions. #116466

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Nov 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions llvm/lib/IR/DIExpressionOptimizer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,14 @@ foldOperationIfPossible(uint64_t Const1, uint64_t Const2,
return Const1 - Const2;
}
case dwarf::DW_OP_shl: {
if ((uint64_t)countl_zero(Const1) < Const2)
if (Const2 >= std::numeric_limits<uint64_t>::digits ||
static_cast<uint64_t>(countl_zero(Const1)) < Const2)
return std::nullopt;
return Const1 << Const2;
}
case dwarf::DW_OP_shr: {
if ((uint64_t)countr_zero(Const1) < Const2)
if (Const2 >= std::numeric_limits<uint64_t>::digits ||
static_cast<uint64_t>(countr_zero(Const1)) < Const2)
return std::nullopt;
return Const1 >> Const2;
}
Expand Down
12 changes: 6 additions & 6 deletions llvm/unittests/IR/MetadataTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3541,38 +3541,38 @@ TEST_F(DIExpressionTest, Fold) {
ResExpr = DIExpression::get(Context, ResOps);
EXPECT_EQ(E, ResExpr);

// Test a left shift greater than 64.
// Test a left shift greater than 63.
Ops.clear();
Ops.push_back(dwarf::DW_OP_constu);
Ops.push_back(1);
Ops.push_back(dwarf::DW_OP_constu);
Ops.push_back(65);
Ops.push_back(64);
Ops.push_back(dwarf::DW_OP_shl);
Expr = DIExpression::get(Context, Ops);
E = Expr->foldConstantMath();
ResOps.clear();
ResOps.push_back(dwarf::DW_OP_constu);
ResOps.push_back(1);
ResOps.push_back(dwarf::DW_OP_constu);
ResOps.push_back(65);
ResOps.push_back(64);
ResOps.push_back(dwarf::DW_OP_shl);
ResExpr = DIExpression::get(Context, ResOps);
EXPECT_EQ(E, ResExpr);

// Test a right shift greater than 64.
// Test a right shift greater than 63.
Ops.clear();
Ops.push_back(dwarf::DW_OP_constu);
Ops.push_back(1);
Ops.push_back(dwarf::DW_OP_constu);
Ops.push_back(65);
Ops.push_back(64);
Ops.push_back(dwarf::DW_OP_shr);
Expr = DIExpression::get(Context, Ops);
E = Expr->foldConstantMath();
ResOps.clear();
ResOps.push_back(dwarf::DW_OP_constu);
ResOps.push_back(1);
ResOps.push_back(dwarf::DW_OP_constu);
ResOps.push_back(65);
ResOps.push_back(64);
ResOps.push_back(dwarf::DW_OP_shr);
ResExpr = DIExpression::get(Context, ResOps);
EXPECT_EQ(E, ResExpr);
Expand Down
Loading