Asik
Asik

Reputation: 22133

Array Bounds Check Elimination in the CLR?

I was recently reading this article by Dave Detlefs in which he presents a few cases where the CLR performs array bounds check elimination. I decided to test this myself, so I did the following:

So here's the dissassembly for a[i] = i; in Test_SimpleAscend:

                a[i] = i;
00000024  mov         eax,dword ptr [ebp-4] 
00000027  mov         edx,dword ptr [ebp-8] 
0000002a  cmp         eax,dword ptr [edx+4] 
0000002d  jb          00000034 
0000002f  call        64FD6E08 
00000034  mov         ecx,dword ptr [ebp-4] 
00000037  mov         dword ptr [edx+eax*4+8],ecx 

The cmp/jb/call is bounds checking, actually forcing the call to be executed throws an IndexOutOfRangeException.

Same thing for all array accesses, including the redundant access in Test_SimpleRedundant. So is there something wrong with my testing methodology, or the CLR doesn't actually eliminate bounds checking? I hope I'm wrong and if so I'd like to know how I can really get array bounds checking elimination.

Upvotes: 7

Views: 5003

Answers (1)

Asik
Asik

Reputation: 22133

Thanks to a comment by Cody Gray, I've managed to answer my own question:

By default, JIT Optimizations are disabled when debugging. To fix this, one can go to Debug -> Options and Settings -> Debugging -> General, and uncheck both "Enable Just My Code" and "Suppress JIT Optimization on module load".

Also see https://learn.microsoft.com/en-us/visualstudio/debugger/jit-optimization-and-debugging

With optimization enabled, the bounds check are removed as advertised.

I'll leave this here for documentation purposes.

Upvotes: 14

Related Questions