Why doesn't gcc optimize matching throw and catch?

Viewed 98

Consider this snippet:

static inline void g() {
    throw 10;
}

int f() {
    try {
        g();
    } catch (const int &x) {
        return x;
    }
    return 0;
}

As you can see from the Compiler Explorer, GCC is able to inline the call to g, but still goes through the whole process of throwing and catching the expression, calling the runtime library. Is there any reason why GCC couldn't just compile f to mov eax, 10; ret? The same happens with clang, with little differences.

An optimization like this would seem when the compiler can inline the throwing site inside the catching site, which perhaps would happen frequently if you call some throwing STL method and catch just outside the call. I guess that avoiding going through the runtime could be a significant improvement in hot loops.

0 Answers
Related