Skip to content

Commit 7ed9819

Browse files
authored
fix(LLVM 23): explicitly truncate values in const_int (#711)
Fixes: #709
1 parent 11a9213 commit 7ed9819

2 files changed

Lines changed: 20 additions & 1 deletion

File tree

src/types/int_type.rs

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@ impl<'ctx> IntType<'ctx> {
8686
}
8787

8888
/// Creates an `IntValue` representing a constant value of this `IntType`. It will be automatically assigned this `IntType`'s `Context`.
89+
/// Note the bits in `value` beyond the width of this integer type are discarded.
8990
///
9091
/// # Example
9192
/// ```no_run
@@ -97,7 +98,14 @@ impl<'ctx> IntType<'ctx> {
9798
/// let i32_value = i32_type.const_int(42, false);
9899
/// ```
99100
// TODOC: Maybe better explain sign extension
100-
pub fn const_int(self, value: u64, sign_extend: bool) -> IntValue<'ctx> {
101+
pub fn const_int(self, mut value: u64, sign_extend: bool) -> IntValue<'ctx> {
102+
// LLVM 23 no longer truncates implicitly, so truncate explicitly to preserve the
103+
// existing behavior: https://github.com/llvm/llvm-project/pull/171456.
104+
let bit_width = self.get_bit_width();
105+
if bit_width < u64::BITS {
106+
value &= (1 << bit_width) - 1;
107+
}
108+
101109
unsafe { IntValue::new(LLVMConstInt(self.as_type_ref(), value, sign_extend as i32)) }
102110
}
103111

tests/all/test_values.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1719,3 +1719,14 @@ fn test_basic_value_types() {
17191719
assert!(scalable_vec_val.as_any_value_enum().is_scalable_vector_value());
17201720
assert!(ppc_f128_val.as_any_value_enum().is_float_value());
17211721
}
1722+
1723+
#[test]
1724+
fn test_const_int_truncation() {
1725+
let context = Context::create();
1726+
let i32_type = context.i32_type();
1727+
1728+
let u32_max_in_u32 = i32_type.const_int(u64::from(u32::MAX), false);
1729+
let u64_max_in_u32 = i32_type.const_int(u64::MAX, false);
1730+
1731+
assert_eq!(u32_max_in_u32, u64_max_in_u32);
1732+
}

0 commit comments

Comments
 (0)