Skip to content

Commit 9396ad6

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

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
@@ -349,8 +349,14 @@ module IteratorsMD
349349
# AbstractArray implementation
350350
Base.axes(iter::CartesianIndices{N,R}) where {N,R} = map(Base.axes1, iter.indices)
351351
Base.IndexStyle(::Type{CartesianIndices{N,R}}) where {N,R} = IndexCartesian()
352-
@propagate_inbounds function Base.getindex(iter::CartesianIndices{N,R}, I::Vararg{Int, N}) where {N,R}
353-
CartesianIndex(getindex.(iter.indices, I))
352+
@inline function Base.getindex(iter::CartesianIndices{N,R}, I::Vararg{Int, N}) where {N,R}
353+
# Eagerly do boundscheck before calculating each item of the CartesianIndex so that
354+
# we can pass `@inbounds` hint to inside the map and generates more efficient SIMD codes (#42115)
355+
@boundscheck checkbounds(iter, I...)
356+
index = map(iter.indices, I) do r, i
357+
@inbounds getindex(r, i)
358+
end
359+
CartesianIndex(index)
354360
end
355361

356362
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)