Skip to content

Commit 6fb00b1

Browse files
authored
Rollup merge of #143477 - folkertdev:use-is-multiple-of, r=joshtriplett
use `is_multiple_of` and `div_ceil` In tricky logic, these functions are much more informative than the manual implementations. They also catch subtle bugs: - the manual `is_multiple_of` often does not handle division by zero - manual `div_ceil` often does not consider overflow The transformation is free for `is_multiple_of` if the divisor is compile-time known to be non-zero. For `div_ceil` there is a small cost to considering overflow. Here is some assembly https://godbolt.org/z/5zP8KaE1d.
2 parents 19f8ba4 + ed3711e commit 6fb00b1

File tree

22 files changed

+33
-34
lines changed

22 files changed

+33
-34
lines changed

compiler/rustc_abi/src/lib.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -527,8 +527,7 @@ impl Size {
527527
/// not a multiple of 8.
528528
pub fn from_bits(bits: impl TryInto<u64>) -> Size {
529529
let bits = bits.try_into().ok().unwrap();
530-
// Avoid potential overflow from `bits + 7`.
531-
Size { raw: bits / 8 + ((bits % 8) + 7) / 8 }
530+
Size { raw: bits.div_ceil(8) }
532531
}
533532

534533
#[inline]

compiler/rustc_borrowck/src/polonius/legacy/location.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,6 @@ impl PoloniusLocationTable {
109109
impl LocationIndex {
110110
fn is_start(self) -> bool {
111111
// even indices are start points; odd indices are mid points
112-
(self.index() % 2) == 0
112+
self.index().is_multiple_of(2)
113113
}
114114
}

compiler/rustc_codegen_llvm/src/abi.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ impl LlvmType for CastTarget {
146146
"total size {:?} cannot be divided into units of zero size",
147147
self.rest.total
148148
);
149-
if self.rest.total.bytes() % self.rest.unit.size.bytes() != 0 {
149+
if !self.rest.total.bytes().is_multiple_of(self.rest.unit.size.bytes()) {
150150
assert_eq!(self.rest.unit.kind, RegKind::Integer, "only int regs can be split");
151151
}
152152
self.rest.total.bytes().div_ceil(self.rest.unit.size.bytes())

compiler/rustc_codegen_llvm/src/va_arg.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -172,10 +172,10 @@ fn emit_aapcs_va_arg<'ll, 'tcx>(
172172

173173
let gr_type = target_ty.is_any_ptr() || target_ty.is_integral();
174174
let (reg_off, reg_top, slot_size) = if gr_type {
175-
let nreg = (layout.size.bytes() + 7) / 8;
175+
let nreg = layout.size.bytes().div_ceil(8);
176176
(gr_offs, gr_top, nreg * 8)
177177
} else {
178-
let nreg = (layout.size.bytes() + 15) / 16;
178+
let nreg = layout.size.bytes().div_ceil(16);
179179
(vr_offs, vr_top, nreg * 16)
180180
};
181181

compiler/rustc_const_eval/src/interpret/memory.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -537,7 +537,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
537537

538538
#[inline]
539539
fn is_offset_misaligned(offset: u64, align: Align) -> Option<Misalignment> {
540-
if offset % align.bytes() == 0 {
540+
if offset.is_multiple_of(align.bytes()) {
541541
None
542542
} else {
543543
// The biggest power of two through which `offset` is divisible.
@@ -1554,7 +1554,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
15541554
// If the allocation is N-aligned, and the offset is not divisible by N,
15551555
// then `base + offset` has a non-zero remainder after division by `N`,
15561556
// which means `base + offset` cannot be null.
1557-
if offset.bytes() % info.align.bytes() != 0 {
1557+
if !offset.bytes().is_multiple_of(info.align.bytes()) {
15581558
return interp_ok(false);
15591559
}
15601560
// We don't know enough, this might be null.

compiler/rustc_index/src/bit_set.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1744,13 +1744,13 @@ impl<R: Idx, C: Idx> SparseBitMatrix<R, C> {
17441744

17451745
#[inline]
17461746
fn num_words<T: Idx>(domain_size: T) -> usize {
1747-
(domain_size.index() + WORD_BITS - 1) / WORD_BITS
1747+
domain_size.index().div_ceil(WORD_BITS)
17481748
}
17491749

17501750
#[inline]
17511751
fn num_chunks<T: Idx>(domain_size: T) -> usize {
17521752
assert!(domain_size.index() > 0);
1753-
(domain_size.index() + CHUNK_BITS - 1) / CHUNK_BITS
1753+
domain_size.index().div_ceil(CHUNK_BITS)
17541754
}
17551755

17561756
#[inline]

compiler/rustc_passes/src/liveness/rwu_table.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ impl RWUTable {
4444
const WORD_RWU_COUNT: usize = Self::WORD_BITS / Self::RWU_BITS;
4545

4646
pub(super) fn new(live_nodes: usize, vars: usize) -> RWUTable {
47-
let live_node_words = (vars + Self::WORD_RWU_COUNT - 1) / Self::WORD_RWU_COUNT;
47+
let live_node_words = vars.div_ceil(Self::WORD_RWU_COUNT);
4848
Self { live_nodes, vars, live_node_words, words: vec![0u8; live_node_words * live_nodes] }
4949
}
5050

compiler/rustc_query_system/src/query/plumbing.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -597,7 +597,7 @@ where
597597
// from disk. Re-hashing results is fairly expensive, so we can't
598598
// currently afford to verify every hash. This subset should still
599599
// give us some coverage of potential bugs though.
600-
let try_verify = prev_fingerprint.split().1.as_u64() % 32 == 0;
600+
let try_verify = prev_fingerprint.split().1.as_u64().is_multiple_of(32);
601601
if std::intrinsics::unlikely(
602602
try_verify || qcx.dep_context().sess().opts.unstable_opts.incremental_verify_ich,
603603
) {

compiler/rustc_serialize/src/leb128.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use crate::serialize::Decoder;
77
/// Returns the length of the longest LEB128 encoding for `T`, assuming `T` is an integer type
88
pub const fn max_leb128_len<T>() -> usize {
99
// The longest LEB128 encoding for an integer uses 7 bits per byte.
10-
(size_of::<T>() * 8 + 6) / 7
10+
(size_of::<T>() * 8).div_ceil(7)
1111
}
1212

1313
/// Returns the length of the longest LEB128 encoding of all supported integer types.

compiler/rustc_span/src/edit_distance.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ pub fn edit_distance_with_substrings(a: &str, b: &str, limit: usize) -> Option<u
130130
1 // Exact substring match, but not a total word match so return non-zero
131131
} else if !big_len_diff {
132132
// Not a big difference in length, discount cost of length difference
133-
score + (len_diff + 1) / 2
133+
score + len_diff.div_ceil(2)
134134
} else {
135135
// A big difference in length, add back the difference in length to the score
136136
score + len_diff

compiler/rustc_target/src/callconv/sparc64.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ where
9090
_ => {}
9191
}
9292

93-
if (offset.bytes() % 4) != 0
93+
if !offset.bytes().is_multiple_of(4)
9494
&& matches!(scalar2.primitive(), Primitive::Float(Float::F32 | Float::F64))
9595
{
9696
offset += Size::from_bytes(4 - (offset.bytes() % 4));
@@ -181,7 +181,7 @@ where
181181
// Structure { float, int, int } doesn't like to be handled like
182182
// { float, long int }. Other way around it doesn't mind.
183183
if data.last_offset < arg.layout.size
184-
&& (data.last_offset.bytes() % 8) != 0
184+
&& !data.last_offset.bytes().is_multiple_of(8)
185185
&& data.prefix_index < data.prefix.len()
186186
{
187187
data.prefix[data.prefix_index] = Some(Reg::i32());
@@ -190,7 +190,7 @@ where
190190
}
191191

192192
let mut rest_size = arg.layout.size - data.last_offset;
193-
if (rest_size.bytes() % 8) != 0 && data.prefix_index < data.prefix.len() {
193+
if !rest_size.bytes().is_multiple_of(8) && data.prefix_index < data.prefix.len() {
194194
data.prefix[data.prefix_index] = Some(Reg::i32());
195195
rest_size = rest_size - Reg::i32().size;
196196
}

compiler/rustc_target/src/callconv/x86.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,7 @@ pub(crate) fn fill_inregs<'a, Ty, C>(
171171
continue;
172172
}
173173

174-
let size_in_regs = (arg.layout.size.bits() + 31) / 32;
174+
let size_in_regs = arg.layout.size.bits().div_ceil(32);
175175

176176
if size_in_regs == 0 {
177177
continue;

compiler/rustc_target/src/callconv/x86_64.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ where
9595
Ok(())
9696
}
9797

98-
let n = ((arg.layout.size.bytes() + 7) / 8) as usize;
98+
let n = arg.layout.size.bytes().div_ceil(8) as usize;
9999
if n > MAX_EIGHTBYTES {
100100
return Err(Memory);
101101
}

compiler/rustc_target/src/callconv/xtensa.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ where
5454
// Determine the number of GPRs needed to pass the current argument
5555
// according to the ABI. 2*XLen-aligned varargs are passed in "aligned"
5656
// register pairs, so may consume 3 registers.
57-
let mut needed_arg_gprs = (size + 32 - 1) / 32;
57+
let mut needed_arg_gprs = size.div_ceil(32);
5858
if needed_align == 64 {
5959
needed_arg_gprs += *arg_gprs_left % 2;
6060
}

compiler/rustc_ty_utils/src/layout/invariant.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use rustc_middle::ty::layout::{HasTyCtxt, LayoutCx, TyAndLayout};
88
pub(super) fn layout_sanity_check<'tcx>(cx: &LayoutCx<'tcx>, layout: &TyAndLayout<'tcx>) {
99
let tcx = cx.tcx();
1010

11-
if layout.size.bytes() % layout.align.abi.bytes() != 0 {
11+
if !layout.size.bytes().is_multiple_of(layout.align.abi.bytes()) {
1212
bug!("size is not a multiple of align, in the following layout:\n{layout:#?}");
1313
}
1414
if layout.size.bytes() >= tcx.data_layout.obj_size_bound() {

library/core/src/slice/mod.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1316,7 +1316,7 @@ impl<T> [T] {
13161316
assert_unsafe_precondition!(
13171317
check_language_ub,
13181318
"slice::as_chunks_unchecked requires `N != 0` and the slice to split exactly into `N`-element chunks",
1319-
(n: usize = N, len: usize = self.len()) => n != 0 && len % n == 0,
1319+
(n: usize = N, len: usize = self.len()) => n != 0 && len.is_multiple_of(n),
13201320
);
13211321
// SAFETY: Caller must guarantee that `N` is nonzero and exactly divides the slice length
13221322
let new_len = unsafe { exact_div(self.len(), N) };
@@ -1512,7 +1512,7 @@ impl<T> [T] {
15121512
assert_unsafe_precondition!(
15131513
check_language_ub,
15141514
"slice::as_chunks_unchecked requires `N != 0` and the slice to split exactly into `N`-element chunks",
1515-
(n: usize = N, len: usize = self.len()) => n != 0 && len % n == 0
1515+
(n: usize = N, len: usize = self.len()) => n != 0 && len.is_multiple_of(n)
15161516
);
15171517
// SAFETY: Caller must guarantee that `N` is nonzero and exactly divides the slice length
15181518
let new_len = unsafe { exact_div(self.len(), N) };
@@ -4866,7 +4866,7 @@ impl<T> [T] {
48664866

48674867
let byte_offset = elem_start.wrapping_sub(self_start);
48684868

4869-
if byte_offset % size_of::<T>() != 0 {
4869+
if !byte_offset.is_multiple_of(size_of::<T>()) {
48704870
return None;
48714871
}
48724872

@@ -4920,7 +4920,7 @@ impl<T> [T] {
49204920

49214921
let byte_start = subslice_start.wrapping_sub(self_start);
49224922

4923-
if byte_start % size_of::<T>() != 0 {
4923+
if !byte_start.is_multiple_of(size_of::<T>()) {
49244924
return None;
49254925
}
49264926

library/core/src/slice/sort/shared/smallsort.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -823,7 +823,7 @@ unsafe fn bidirectional_merge<T: FreezeMarker, F: FnMut(&T, &T) -> bool>(
823823
let right_end = right_rev.wrapping_add(1);
824824

825825
// Odd length, so one element is left unconsumed in the input.
826-
if len % 2 != 0 {
826+
if !len.is_multiple_of(2) {
827827
let left_nonempty = left < left_end;
828828
let last_src = if left_nonempty { left } else { right };
829829
ptr::copy_nonoverlapping(last_src, dst, 1);

library/core/src/slice/sort/stable/drift.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@ fn merge_tree_scale_factor(n: usize) -> u64 {
158158
panic!("Platform not supported");
159159
}
160160

161-
((1 << 62) + n as u64 - 1) / n as u64
161+
(1u64 << 62).div_ceil(n as u64)
162162
}
163163

164164
// Note: merge_tree_depth output is < 64 when left < right as f*x and f*y must
@@ -182,7 +182,7 @@ fn sqrt_approx(n: usize) -> usize {
182182
// Finally we note that the exponentiation / division can be done directly
183183
// with shifts. We OR with 1 to avoid zero-checks in the integer log.
184184
let ilog = (n | 1).ilog2();
185-
let shift = (1 + ilog) / 2;
185+
let shift = ilog.div_ceil(2);
186186
((1 << shift) + (n >> shift)) / 2
187187
}
188188

library/core/src/str/count.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ fn do_count_chars(s: &str) -> usize {
5252
// Check the properties of `CHUNK_SIZE` and `UNROLL_INNER` that are required
5353
// for correctness.
5454
const _: () = assert!(CHUNK_SIZE < 256);
55-
const _: () = assert!(CHUNK_SIZE % UNROLL_INNER == 0);
55+
const _: () = assert!(CHUNK_SIZE.is_multiple_of(UNROLL_INNER));
5656

5757
// SAFETY: transmuting `[u8]` to `[usize]` is safe except for size
5858
// differences which are handled by `align_to`.

library/core/src/str/iter.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ impl<'a> Iterator for Chars<'a> {
102102
// `(len + 3)` can't overflow, because we know that the `slice::Iter`
103103
// belongs to a slice in memory which has a maximum length of
104104
// `isize::MAX` (that's well below `usize::MAX`).
105-
((len + 3) / 4, Some(len))
105+
(len.div_ceil(4), Some(len))
106106
}
107107

108108
#[inline]
@@ -1532,11 +1532,11 @@ impl<'a> Iterator for EncodeUtf16<'a> {
15321532
// belongs to a slice in memory which has a maximum length of
15331533
// `isize::MAX` (that's well below `usize::MAX`)
15341534
if self.extra == 0 {
1535-
((len + 2) / 3, Some(len))
1535+
(len.div_ceil(3), Some(len))
15361536
} else {
15371537
// We're in the middle of a surrogate pair, so add the remaining
15381538
// surrogate to the bounds.
1539-
((len + 2) / 3 + 1, Some(len + 1))
1539+
(len.div_ceil(3) + 1, Some(len + 1))
15401540
}
15411541
}
15421542
}

library/core/src/str/validations.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -219,7 +219,7 @@ pub(super) const fn run_utf8_validation(v: &[u8]) -> Result<(), Utf8Error> {
219219
// Ascii case, try to skip forward quickly.
220220
// When the pointer is aligned, read 2 words of data per iteration
221221
// until we find a word containing a non-ascii byte.
222-
if align != usize::MAX && align.wrapping_sub(index) % USIZE_BYTES == 0 {
222+
if align != usize::MAX && align.wrapping_sub(index).is_multiple_of(USIZE_BYTES) {
223223
let ptr = v.as_ptr();
224224
while index < blocks_end {
225225
// SAFETY: since `align - index` and `ascii_block_size` are

library/portable-simd/crates/core_simd/src/lane_count.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ pub struct LaneCount<const N: usize>;
88

99
impl<const N: usize> LaneCount<N> {
1010
/// The number of bytes in a bitmask with this many lanes.
11-
pub const BITMASK_LEN: usize = (N + 7) / 8;
11+
pub const BITMASK_LEN: usize = N.div_ceil(8);
1212
}
1313

1414
/// Statically guarantees that a lane count is marked as supported.

0 commit comments

Comments
 (0)