Skip to content

Commit 58cbcf3

Browse files
johnnychen94KristofferC
authored andcommitted
Eagerly do boundscheck when indexing into CartesianIndices (#42119)
(cherry picked from commit 15b9851)
1 parent f256354 commit 58cbcf3

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

base/multidimensional.jl

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -353,8 +353,14 @@ module IteratorsMD
353353
# AbstractArray implementation
354354
Base.axes(iter::CartesianIndices{N,R}) where {N,R} = map(Base.axes1, iter.indices)
355355
Base.IndexStyle(::Type{CartesianIndices{N,R}}) where {N,R} = IndexCartesian()
356-
@propagate_inbounds function Base.getindex(iter::CartesianIndices{N,R}, I::Vararg{Int, N}) where {N,R}
357-
CartesianIndex(getindex.(iter.indices, I))
356+
@inline function Base.getindex(iter::CartesianIndices{N,R}, I::Vararg{Int, N}) where {N,R}
357+
# Eagerly do boundscheck before calculating each item of the CartesianIndex so that
358+
# we can pass `@inbounds` hint to inside the map and generates more efficient SIMD codes (#42115)
359+
@boundscheck checkbounds(iter, I...)
360+
index = map(iter.indices, I) do r, i
361+
@inbounds getindex(r, i)
362+
end
363+
CartesianIndex(index)
358364
end
359365

360366
ndims(R::CartesianIndices) = ndims(typeof(R))

test/boundscheck_exec.jl

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -259,4 +259,17 @@ if bc_opt == bc_default || bc_opt == bc_off
259259
@test !occursin("arrayref(true", typed_40281)
260260
end
261261

262+
@testset "pass inbounds meta to getindex on CartesianIndices (#42115)" begin
263+
@inline getindex_42115(r, i, j) = @inbounds getindex(r, i, j)
264+
265+
R = CartesianIndices((5, 5))
266+
if bc_opt == bc_on
267+
@test_throws BoundsError getindex_42115(R, -1, -1)
268+
@test_throws BoundsError getindex_42115(R, 1, -1)
269+
else
270+
@test getindex_42115(R, -1, -1) == CartesianIndex(-1, -1)
271+
@test getindex_42115(R, 1, -1) == CartesianIndex(1, -1)
272+
end
273+
end
274+
262275
end

0 commit comments

Comments
 (0)