1.3 Controlling Optimization with Pragmas

Occasionally you will need to exercise a fine level of control over compiler optimizations. Command-line options allow you to control optimization over an entire compilation unit (file). In addition, Microsoft C/C++ supports several pragmas that allow you to exercise such control on a per-function basis.

The pragmas that control optimization are described in this chapter under the type of optimization they affect.

You can control each of the following optimization parameters on a function-by-function basis using the optimize pragma:

Behavior of code with respect to aliasing (a and w)

Inlining of function calls (b0, b1, or b2)

Reduction of local common subexpressions (c)

Reduction of global common subexpressions (g)

Global register allocation (e)

Loop optimization (l)

Maximization of optimizations (x)

Aggressiveness of optimizations (z)

Disabling of unsafe optimizations (n)

Achieving consistent floating-point results (p)

Use of a single exit point for each function (r)

Optimizing for smaller code size or for faster execution speed (s or t)

There is also an option for compiling your program into p-code (/Oq), and options that apply only when p-code is enabled (/Of, /Of–, /Ov, and /Ov–). See Chapter 3, “Reducing Program Size with P-Code,” for information on these options.

Any optimization or combination of options can be enabled or disabled using the optimize pragma. For example, if you have one function that uses aliases heavily, you need to inhibit optimizations that could cause problems with aliases. You do not, however, want to inhibit these optimizations for code that does not do aliasing. To do this, use the optimize pragma as follows:

/* Function(s) that do not do aliasing. */

.

.

.

#pragma optimize( “a”, off )

/* Function(s) that do aliasing. */

.

.

.

#pragma optimize( “a”, on )

/* More function(s) that do not do aliasing. */

The parameters to the optimize pragma can be combined in a string to enable or disable multiple options at once. For example,

#pragma optimize( “lge”, off )

disables loop optimization, global common subexpression optimization, and global register allocation.