Posts Tagged ‘VC’

Counterpart of __assume in GCC

Microsoft Visual C++ has a keyword __assume, which is used to pass a hint to the compiler for optimization. It can be useful when optimizing hotspots in a program. For example, if we know a loop will run at least once, we can add an __assume hint:

__assume (0 < n);
for (i=0; i < n; i++)
    /* .... */

This eliminates the comparison of n against zero before entering the loop body for the first time, without changing it to a do-while structure, which is usually less preferable than a for loop. Another typical use is to tell the compiler the default branch of a switch-case statement is unreachable.

GCC does not have a counterpart. But now that GCC 4.5.0 introduced __builtin_unreachable, we can do everything in GCC what we do with __assume in MSVC. My tests show the following macro works:

#define __assume(cond) do { if (!(cond)) __builtin_unreachable(); } while (0)

(The “do { ... } while (0)” statement is just a small trick in defining macros. Actually it’s been so well known and widely used that it can hardly be called a trick anymore.)

Tags: ,