cost of @safe and safety inference

monarch_dodra monarchdodra at gmail.com
Mon Mar 11 07:57:20 PDT 2013


I was on vacation last week, mostly without internet and even 
less D, which gave me the time to have existential thoughts 
(about D ^^).

The issue I'm thinking about is @safe. @safe has a double 
function:
1) Restrict any any usage of "unsafe" code.
2) Bounds check slices, even in release mode.

I think that when you ask for safe code, then 1) is always 
desired. 2), on the other hand, and not always desired. In 
particular, the only way to turn off 2) is with the global 
"-noboundscheck" hook.

...

Things get fun with D's attribute inference. As you know, D is 
able to infer if a function is nothrow... or safe!

So here's the kicker: You wrote a template that is potentially 
safe. The D compiler tags it as safe. Awesome. BUT, because it's 
safe, it also means it is bounds checked, even in release. Not 
only is this (probably) not desired, but it is also *very* 
not-obvious.

Take this "dumb" program:

//----
int[] a;

int foo()()
{
     return a[4];
}
void main()
{
   a = [1, 2, 3];
   foo!()();
}
//----

You know what you get in release? A range error because foo!() is 
safe, and the compiler generated the associated bounds checking. 
To override this, foo must be explicitly tagged as @system.

FACT: I have NEVER seen ANYBODY use @system, be it in phobos, or 
user code.

This is counter intuitive, because for normal functions, @safe is 
"opt-in". For templates though, when possible, safety becomes 
opt-*out*. Weird 0_o.

Has anybody else though about these kinds of issues before? I'm 
wondering how many of our algorithm benchmarks this has 
clobbered, and in which ratio this could be a factor of D's "bad" 
performance relative to C++?.


----------------------------------------------------------
----------------------------------------------------------


Solution?

This may be crazy, but given that "safe" is not free, I think 
"default" safety inference should be dropped.

However, templates would have an opt-in "safe if possible" 
keyword "@optsafe":

A template marked "@optsafe" would ban any unsafe code that does 
not depend on parametrization. It would always check bounds of 
arrays (provided no -noboundscheck).

However, if at the end of the day, there is unsafe parametrized 
usage, then the final template just won't be marked as @safe.

Thoughts?


More information about the Digitalmars-d mailing list