Array bound checks removal increasing importance

bearophile via Digitalmars-d digitalmars-d at puremagic.com
Thu Jun 5 03:34:01 PDT 2014


Dmitry Olshansky:

> It would be interesting if you could point to a precedent of 
> expression-level attribute used for enforcing that compiler 
> does elide bounds checking

Perhaps that's a little invention of mine :-)

In the last years I've seen that while optimizations are 
important, there are situations where you need to know if an 
optimization is done. Array bound checks removal is not able to 
change the code semantics like tail call optimization (TCO), but 
like forced inlining you sometimes want to be sure a small amount 
of lines of a numeric processing kernel doesn't waste run time 
verifying bounds.

(And if you are sure certain bound checks are not present, you 
have also verified that a part of the code doesn't raise array 
bound run-time errors. So it's also a code verification 
technique, that I think will become more common in the next 
years).

If you write a contract between the compiler and the programmer, 
and it fails (so the compiler is not able to remove all bound 
checks in a piece of D code inside the @bounded { ... }), then 
the programmer can add strongly typed indexes to help the 
compiler figure out at compile time the correctness of array 
accesses (strongly typed array indexes that I have discussed in a 
recent thread are indeed also useful for the compiler 
optimizations, they are not just to help avoid programmers bugs), 
or the programmer can add some asserts or change the code in 
other small ways to reach the same goal. Once such goal is 
reached, and your kernel computation is efficient, you don't care 
if in some cases in the rest of the code the D compiler is not 
able to remove all array bound checks. So only a small/certain 
percentage of the code is meant to go inside the braces of 
@bounded{...}. The alternative solution is to put the kernel into 
another module, and compile it separately with 
"-boundscheck=off". But this is less handy and it's less safe.

Generally I like ways to express a richer semantics in the code.

Bye,
bearophile


More information about the Digitalmars-d mailing list