On 7/28/2014 1:42 AM, bearophile wrote:
void main() {
     import std.stdio, core.checkedint;

     ubyte x = 100;
     ubyte y = 200;

     bool overflow = false;
     immutable result = muls(x, y, overflow);
     assert(!overflow);
     writeln("Product: ", result);
}


Here I am not willing to add an assume(). Here at the call point of muls() x and
y have a full range of ubytes, so the range analysis tell the compiler their
product will not overflow, so it can replace the muls() with a regular product
and leave overflow untouched. This is faster.

Here there are no new language features required. muls() being an intrinsic means the compiler knows about it. The compiler already does data flow analysis on constants, meaning it knows that x is 100, and will replace subsequent instances of x with 100. This is called "constant propagation", and has been a standard feature of compilers for 30 years.

Some optimizers (not including dmd's) go further with this data flow analysis and do ranges. assert()s are mined by the optimizer for information about ranges. ('assume' adds absolutely nothing here.) With this, since the compiler knows about muls(), it can optimize it.

The point being:

    NO NEW LANGUAGE FEATURES ARE NECESSARY

bearophile, I know you are interested in these sorts of things, but you are unaware of routine data flow analysis that compilers have done for decades. I strongly recommend you pick up a compiler book like "Compilers Principles Techniques and Tools" and thumb through the optimization section. I think you'll find it enjoyable and useful.

Reply via email to