Asserts & optimisation (repost from com.lang.c++)

"David Fisher" <nospam@nospam.nospam.nospam>
3 Dec 2003 20:28:32 -0500

          From comp.compilers

Related articles
Asserts & optimisation (repost from com.lang.c++) nospam@nospam.nospam.nospam (David Fisher) (2003-12-03)
Re: Asserts & optimisation (repost from comp.lang.c++) (2003-12-08)
Re: Asserts & optimisation (repost from com.lang.c++) (2003-12-08)
| List of all articles for this month |

From: "David Fisher" <nospam@nospam.nospam.nospam>
Newsgroups: comp.compilers
Date: 3 Dec 2003 20:28:32 -0500
Organization: Pacific Internet (Australia)
Keywords: C++, optimize
Posted-Date: 03 Dec 2003 20:28:32 EST

This comment from jeffc sparked a thought:

> The assert doesn't do anything in a release build, and that
> is its advantage, you can afford to put more tests into your
> code then you ever would if the tests were to be exercised
> in release versions.
> Would we ever put a check for validity into every method of
> our Point class if it were to be exercised in customer
> builds? Of course not, the test will be exercised millions
> of times
> ...

Error checking (and recovery) in itself isn't a bad thing in a release
build - it's the cost that people object to. A really clever compiler
could potentially take care of this problem - for example:

T& Array::operator [] (int index)
        assert(index >= 0 && index < arrayLength);
        return arrayVal[index];

void incrementValues(Array &a)
        for (int n = 0;n < a.length();++n)

An intelligent compiler could recognise that in this particular loop,
the assert condition is always false, and so the check is not
necessary at run time.

Has anyone ever seen an optimising compiler that actually does
this ?

This would require:

- data flow analysis across function boundaries
- some way of preventing execution of the "assert" code:
    - multiple entry points to functions with preconditions ?
    - multiple versions of functions, with and without checks ?
        (similar to the code generation done by templates)
        (but avoid having 2^N versions of a function with N asserts !)
- possibly embedding this information in object modules / libraries
    so separate compilation is handled, too

This applies to "optimising out" any block of code the compiler
knows will never be entered, not just asserts like this one.

David F

Post a followup to this message

Return to the comp.compilers page.
Search the comp.compilers archives again.