Skip to content

Commit

Permalink
Rollup merge of #91162 - RalfJung:miri-shift-truncation, r=oli-obk
Browse files Browse the repository at this point in the history
explain why CTFE/Miri perform truncation on shift offset

Closes rust-lang/miri#1920
  • Loading branch information
matthiaskrgr authored Nov 25, 2021
2 parents 5f6cb2c + 5f6ccf6 commit 5fff1d7
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
7 changes: 6 additions & 1 deletion compiler/rustc_const_eval/src/interpret/operator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,12 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
let signed = left_layout.abi.is_signed();
let size = u128::from(left_layout.size.bits());
let overflow = r >= size;
let r = r % size; // mask to type size
// The shift offset is implicitly masked to the type size, to make sure this operation
// is always defined. This is the one MIR operator that does *not* directly map to a
// single LLVM operation. See
// <https://github.com/rust-lang/rust/blob/a3b9405ae7bb6ab4e8103b414e75c44598a10fd2/compiler/rustc_codegen_ssa/src/common.rs#L131-L158>
// for the corresponding truncation in our codegen backends.
let r = r % size;
let r = u32::try_from(r).unwrap(); // we masked so this will always fit
let result = if signed {
let l = self.sign_extend(l, left_layout) as i128;
Expand Down
8 changes: 8 additions & 0 deletions compiler/rustc_middle/src/mir/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2246,8 +2246,12 @@ pub enum BinOp {
/// The `*` operator (multiplication)
Mul,
/// The `/` operator (division)
///
/// Division by zero is UB.
Div,
/// The `%` operator (modulus)
///
/// Using zero as the modulus (second operand) is UB.
Rem,
/// The `^` operator (bitwise xor)
BitXor,
Expand All @@ -2256,8 +2260,12 @@ pub enum BinOp {
/// The `|` operator (bitwise or)
BitOr,
/// The `<<` operator (shift left)
///
/// The offset is truncated to the size of the first operand before shifting.
Shl,
/// The `>>` operator (shift right)
///
/// The offset is truncated to the size of the first operand before shifting.
Shr,
/// The `==` operator (equality)
Eq,
Expand Down

0 comments on commit 5fff1d7

Please sign in to comment.