C++ Optimizations in MSVC Build Tools 14.52
The Microsoft C++ team implemented new optimizations in MSVC Build Tools 14.52. Let’s walk through examples of some of these optimizations. We will focus on reassociation, loop optimizations, SIMD code generation, inlining, and patterns. Where noted, we’ll also include a few optimizations that appeared in MSVC 14.51 but which were not covered in previous blog posts.
Improved Reassociation
We improved arithmetic reassociation to make shared calculations easier to
identify and eliminate. The compiler is free to reassociate integer expressions
and can reassociate floating-point expressions with /fp:fast.
Previously, the compiler reassociated terms that would simplify, such as
x + y - x, and then rebuilt a balanced expression tree. For example:
(((((a + b) + x) + y) - x) + z) => (a + b) + (y + z)
Although this is good, simplification and balancing alone without regard for common expressions can prevent other optimizations.
Consider this function:
void foo(double x, double y, double z, double d, double* out) {
out[0] = 1.0 + 2.5 * x * x - d;
out[1] = 1.0 + 2.5 * y * y - d;
out[2] = 1.0 + 2.5 * z * z - d;
}
Nothing directly simplifies and there are three addition/subtraction terms so
balancing does not do anything, but all three expressions contain 1.0 - d.
Under /fp:fast, the compiler should arrange for 1.0 - d to occur once:
void foo(double x, double y, double z, double d, double* out) {
double temp = 1.0 - d;
out[0] = temp + 2.5 * x * x;
out[1] = temp + 2.5 * y * y;
out[2] = temp + 2.5 * z * z;
}
The updated compiler performs this reassociation. It groups subexpressions in a ranked order where literals come first, followed by loop invariants, then variants. Grouping invariants next to literals, which are also invariant, helps the compiler to hoist larger expressions from loops. Within the groups, the global frequency of each term is considered, including instances where the term occurs with a different sign. Our algorithm is very similar to the one described in the global reassociation section of the paper Effective Partial Redundancy Elimination by Briggs and Cooper.
For example:
void foo2(int n, int x, int* out, int* out2) {
for (int i = 0; i < n; ++i) {
out[i] = 1 + 2 * i + x;
out2[i] = 1 - 2 * i + x;
}
}
Applying reassociation, hoisting, and common subexpression elimination yields:
void foo2(int n, int x, int* out, int* out2) {
int hoisted = 1 + x;
for (int i = 0; i < n; ++i) {
int temp = 2 * i;
out[i] = hoisted + temp;
out2[i] = hoisted - temp;
}
}
Loop Optimizations
Loop final value optimization
The loop optimizer can replace a repeated induction variable update with a calculation of its final value. When the intermediate values are not needed inside the loop, the updates can be removed. If nothing else remains in the loop, then the loop itself can be removed.
For example, a constant increment repeated a known number of times:
result = 0;
for (int i = 0; i < 10; i++) {
result += 5;
}
can become:
result = 50;
Other work in the loop does not necessarily prevent final-value optimization.
In this example, printing still requires iteration, but updating result does
not:
result = 0;
for (int i = 0; i < 10; i++) {
print(i);
result += 5;
}
The transformed code keeps the printing loop and materializes the result afterward:
for (int i = 0; i < 10; i++) {
print(i);
}
result = 50;
A runtime trip count can also be handled:
result = 0;
for (int i = 0; i < n; i++) {
result += 5;
}
becomes:
result = n > 0 ? n * 5 : 0;
The zero-trip case is preserved. These transformations assume that the compiler can establish the conditions needed to preserve the original program’s behavior.
Better address modes in loops
Address calculations are now optimized with more information about the entire
loop, rather than choosing the largest addressing mode for each instruction in
isolation. The work spans arithmetic-expression reordering, loop-invariant code
motion, common-subexpression elimination, and address-mode construction. The
optimization was motivated by unrolled loops where nearby memory accesses can
share a common base address. It is especially useful on ARM64, where
neighboring loads with a common base can be combined into load-pair (LDP)
instructions. For example, consider this sequence of instructions within a loop:
add x28, x8, #1
add x24, x8, #2
add x27, x8, #3
add x20, x8, #4
add x19, x8, #5
add x15, x8, #6
add x23, x8, #7
add x26, x8, #8
add x22, x8, #9
add x14, x8, #10
add x0, x8, #11
add x13, x8, #12
add x1, x8, #13
add x12, x8, #14
add x7, x8, #15
add x11, x8, #16
add x21, x8, #17
add x25, x8, #18
The loop then used 19 individual indexed loads:
ldr d26, [x10, x28, lsl #3]
ldr d25, [x10, x8, lsl #3]
ldr d23, [x10, x24, lsl #3]
ldr d15, [x10, x27, lsl #3]
ldr d14, [x10, x20, lsl #3]
ldr d13, [x10, x19, lsl #3]
ldr d12, [x10, x15, lsl #3]
ldr d0, [x10, x23, lsl #3]
ldr d1, [x10, x26, lsl #3]
ldr d30, [x10, x22, lsl #3]
ldr d29, [x10, x14, lsl #3]
ldr d2, [x10, x0, lsl #3]
ldr d3, [x10, x13, lsl #3]
ldr d4, [x10, x1, lsl #3]
ldr d28, [x10, x12, lsl #3]
ldr d5, [x10, x7, lsl #3]
ldr d6, [x10, x11, lsl #3]
ldr d7, [x10, x21, lsl #3]
ldr d31, [x10, x25, lsl #3]
The improved code calculates a shared base before the loop:
lsl x24, x8, #3
add x28, x24, x10
The loads in the loop use constant offsets from that base, allowing nine pairs and one remaining individual load:
ldp d25, d26, [x28]
ldp d23, d15, [x28, #16]
ldp d14, d13, [x28, #32]
ldp d12, d0, [x28, #48]
ldp d1, d30, [x28, #64]
ldp d29, d2, [x28, #80]
ldp d3, d4, [x28, #96]
ldp d28, d5, [x28, #112]
ldp d6, d7, [x28, #128]
ldr d31, [x28, #144]
Sharing ARM64 address calculations across indexed accesses
Another address-mode improvement targets accesses that share a fixed member offset but use different array indices, such as as neighborhood-pattern computation that loads eight elements from a member array. Each address has the form:
(basePtr + varyingIndex * elementSize) + memberOffset
Previously, the compiler calculated basePtr + varyingIndex * elementSize
separately for each access and folded memberOffset into the load. Although
each address mode was efficient in isolation, the sequence repeated work.
The improved code instead computes a shared base:
sharedBase = basePtr + memberOffset
address = sharedBase + varyingIndex * elementSize
For example, the old ARM64 sequence contained eight address calculations and eight loads. The first two accesses looked like this:
add x8, x19, x10, lsl #2
ldr w0, [x8, #0x500]
add x8, x19, x11, lsl #2
ldr w1, [x8, #0x500]
With the member offset included in a shared base, all eight loads can use scaled-indexed addressing directly:
add x20, x19, #0x500
ldr w0, [x20, x10, lsl #2]
ldr w1, [x20, x11, lsl #2]
ldr w2, [x20, x12, lsl #2]
ldr w3, [x20, x13, lsl #2]
ldr w4, [x20, x14, lsl #2]
ldr w5, [x20, x15, lsl #2]
ldr w6, [x20, x16, lsl #2]
ldr w7, [x20, x17, lsl #2]
This reduces the sequence from 16 instructions to nine. Unlike the preceding load-pair example, the indices can differ; the opportunity is to share the fixed part of the address, not to combine adjacent loads.
Hoisting conditionally executed loop-invariant operations
Loop-invariant code motion can now hoist eligible pure operations even when they originally appeared in a conditional block. The inputs do not change between iterations, so the calculation need not be repeated whenever the condition is true.
For example:
for (int i = 0; i < n; i++) {
if (i % 2) {
sum += a * b;
}
}
can be transformed into:
c = a * b;
for (int i = 0; i < n; i++) {
if (i % 2) {
sum += c;
}
}
The multiplication moves out of the loop and the conditional accumulation stays in place. This is not a general license to move side effects or unsafe operations out of conditional execution.
SIMD Code Generation and Vectorization
Small-loop vectorization on ARM64
Starting in MSVC 14.51, the ARM64 loop vectorizer accepts small loops that exactly fill a vector register, including 64-bit vectors. Previously, a loop such as this was rejected as too small:
void small_loop(int* __restrict a, const int* __restrict b) {
for (int i = 0; i < 2; i++) {
a[i] += b[i];
}
}
Now the loop body vectorizes as:
ldr d17, [x0]
ldr d16, [x1]
add v16.2s, v17.2s, v16.2s
str d16, [x0]
ARM64 NEON bitmask patterns
The first pattern combines negation with a sign test when range information
proves the input to the negation cannot be INT_MIN. For example:
#include <arm_neon.h>
int32x4_t shift_sign_bit_s32(int32x4_t a) {
return vshrq_n_s32(vnegq_s32(vshrq_n_s32(a, 1)), 31);
}
In MSVC 14.50, the sequence was:
sshr v16.4s, v0.4s, #1
neg v16.4s, v16.4s
cmlt v0.4s, v16.4s, #0
In MSVC 14.51, the initial shift supplies the range information needed to replace the last two instructions with a positive comparison:
sshr v16.4s, v0.4s, #1
cmgt v0.4s, v16.4s, #0
The second pattern tests whether all bits above the low byte are zero:
#include <arm_neon.h>
int32x4_t test_int32_t(int32x4_t a) {
return vceqq_s32(vandq_s32(a, vdupq_n_s32(-256)), vdupq_n_s32(0));
}
The literal mask-and-compare implementation in MSVC 14.50:
mvni v16.4s, #0xFF
movi v17.4s, #0
and v16.16b, v0.16b, v16.16b
cmeq v0.4s, v16.4s, v17.4s
is replaced in MSVC 14.51 with an unsigned comparison against 256:
movi v16.4s, #1, lsl #8
cmhi v0.4s, v16.4s, v0.4s
ARM64 NEON pairwise add-and-accumulate patterns
The compiler recognizes a widening pairwise addition followed by accumulation:
#include <arm_neon.h>
uint32x4_t test_uint32x4(uint32x4_t acc, uint16x8_t a) {
const auto pairs = vpaddlq_u16(a);
return vaddq_u32(acc, pairs);
}
Instead of the two instructions emitted by MSVC 14.50:
uaddlp v16.4s, v1.8h
add v0.4s, v0.4s, v16.4s
14.51 emits:
uadalp v0.4s, v1.8h
The signed variant similarly uses SADALP.
SLP recognition of scalar reductions
In MSVC 14.51, superword-level parallelism (SLP) vectorization can recognize scalar reductions such as:
int reduce(const int* a) {
return a[0] + a[1] + a[2] + a[3];
}
ARM64 has a horizontal sum instruction that makes this compact:
ldr q16, [x0]
addv s16, v16.4s
On x64, reducing vector lanes requires a larger sequence. The profitability decision therefore also considers whether other vectorizable operations can offset the reduction cost.
SLP recognition of phi nodes
In MSVC 14.52, SLP can vectorize phi nodes, extending its scope beyond straight-line basic blocks to patterns involving loops. For example, consider two neighboring accumulations:
#include <stdint.h>
void slp_phi(int64_t* dst, const int64_t* src, int n) {
int64_t a = 0;
int64_t b = 0;
for (int i = 0; i < n; i += 2) {
a += src[i];
b += src[i + 1];
}
dst[0] = a;
dst[1] = b;
}
These can be processed as two vector lanes. In static single assignment form, phi nodes merge the initial accumulator values with the values produced by previous loop iterations. Recognizing those nodes allows SLP to follow the accumulations through the loop, rather than stopping at the merge.
The transformation can be illustrated with vectorized SSA pseudocode:
a_0 = broadcast(0)
for (i = 0; i < n; i += 2):
a_1 = phi(a_0, a_2)
a_2 = a_1 + load(&src[i])
a_3 = phi(a_0, a_2)
store(&dst[0], a_3)
Recognizing adjacent data through address arithmetic
In MSVC 14.52, SLP can recognize more neighboring scalar loads and stores even when
their addresses are written differently. A motivating example accessed pairs of
double values using an index calculated at runtime:
int j = 3 * indices[k];
double dx = xi - x[j];
double dy = yi - x[j + 1];
double r2 = dx * dx + dy * dy;
double scale = 1.0 / (r2 * r2);
double fx = scale * dx;
double fy = scale * dy;
f[j] -= fx;
f[j + 1] -= fy;
To vectorize the neighboring operations, SLP must establish that their memory
accesses are adjacent. For an eight-byte double, it can analyze the second
address as:
x + (j + 1) * 8 -> x + j * 8 + 8
Both accesses then have the same variable part, x + j * 8, with byte offsets
of zero and eight.
The address builder already supported this distribution when optimizing address
expressions. The change makes it available in analysis-only mode too, so SLP
can record the constant byte offset and prove adjacency without rewriting the
intermediate representation. This applies to both the x loads and the f
updates.
For example, updating the two force components separately on ARM64 requires two loads, two subtractions, and two stores:
; x0 = &f[j], d0 = fx, d1 = fy
ldr d2, [x0]
ldr d3, [x0, #8]
fsub d2, d2, d0
fsub d3, d3, d1
str d2, [x0]
str d3, [x0, #8]
With both components in a vector register, the update becomes:
; x0 = &f[j], v0.2d = {fx, fy}
ldr q2, [x0]
fsub v2.2d, v2.2d, v0.2d
str q2, [x0]
Optimizing explicit NEON loads and stores
In MSVC 14.52, explicit NEON load and store intrinsics are canonicalized into generic memory operations. Previously, the compiler kept the specific intrinsics throughout the optimizer, but they did not match existing optimization patterns that expected normal loads and stores. Canonicalizing the NEON loads and stores allowed existing optimizations to apply to them. Ultimately, if the loads and stores persist after optimization, they may become NEON loads and stores again.
Combining scalar stores when constructing vectors
MSVC 14.52 extends scalar-store combining to more data types and ARM64 NEON. When scalar assignments construct a vector that is subsequently loaded as a whole, the compiler can build the value directly in registers rather than storing each component to the stack and loading it back.
For example:
#include <arm_neon.h>
float32x4_t make_vector(float a, float b, float c, float d) {
float32x4_t result;
result.n128_f32[0] = a;
result.n128_f32[1] = b;
result.n128_f32[2] = c;
result.n128_f32[3] = d;
return result;
}
The register-only construction can use lane inserts:
ins v0.s[1], v1.s[0]
ins v0.s[2], v2.s[0]
ins v0.s[3], v3.s[0]
This small example already stayed in registers in MSVC 14.51. The improvement is in larger functions, where control flow and register pressure previously prevented the register allocator from eliminating the temporary stack storage. Combining the stores earlier also exposes the vector to later SIMD optimizations.
More robust bit-pattern recognition
MSVC 14.52 improves the cost model for recognizing scalar bit-manipulation patterns when their inputs are defined in another basic block. For example, this sequence reverses the bits of a 32-bit value:
#include <intrin.h>
unsigned int reverse_bits(unsigned int x) {
x = ((x & 0x55555555u) << 1) | ((x & 0xAAAAAAAAu) >> 1);
x = ((x & 0x33333333u) << 2) | ((x & 0xCCCCCCCCu) >> 2);
x = ((x & 0x0F0F0F0Fu) << 4) | ((x & 0xF0F0F0F0u) >> 4);
return _byteswap_ulong(x);
}
On ARM64, the calculation can become:
rbit w0, w0
The isolated pattern was already recognized. The new behavior makes recognition more reliable inside large functions with more complicated control flow.
ARM64 NEON arithmetic with a selected lane
A vector multiplication by a broadcast lane no longer needs a separate duplicate instruction when the arithmetic instruction can select that lane directly:
#include <arm_neon.h>
float32x4_t multiply_by_lane(float32x4_t a, float32x4_t b) {
return vmulq_f32(a, vdupq_laneq_f32(b, 1));
}
MSVC 14.51 emitted:
dup v16.4s, v1.s[1]
fmul v0.4s, v0.4s, v16.4s
MSVC 14.52 folds the broadcast into the multiply:
fmul v0.4s, v0.4s, v1.s[1]
The same recognition applies to fused multiply-add and multiply-subtract,
using the by-element forms of FMLA and FMLS. With /fp:fast, the compiler
can also exchange the multiplicands to expose these forms when the broadcast
appears on the other side of the multiplication.
ARM64 NEON shifted bit-clear patterns
The compiler can combine a mask and shift by moving the mask after the shift and expressing it as an immediate bit-clear operation:
#include <arm_neon.h>
int32x4_t mask_and_shift(int32x4_t a) {
return vshlq_n_s32(vandq_s32(a, vdupq_n_s32(2)), 30);
}
Previously, this required loading the mask, applying it, and shifting:
movi v16.4s, #2
and v16.16b, v0.16b, v16.16b
shl v0.4s, v16.4s, #30
MSVC 14.52 instead emits:
shl v0.4s, v0.4s, #30
bic v0.4s, #0x40, lsl #24
The shifted result can contain only bits 30 and 31. Clearing bit 30 leaves exactly the bit selected by the original mask, without materializing a vector constant.
Removing masks made redundant by a shift
In related cases, the mask can disappear entirely:
#include <arm_neon.h>
int32x4_t move_low_bit(int32x4_t a) {
return vshlq_n_s32(vandq_s32(a, vdupq_n_s32(1)), 31);
}
Only the original low bit survives a 31-bit left shift, so masking off the
other bits beforehand does not affect the result. Instead of a MOVI, AND,
and SHL, MSVC 14.52 needs only:
shl v0.4s, v0.4s, #31
Removing work in unused NEON lanes
MSVC 14.52 tracks which vector lanes are observed and can remove instructions that define only unused lanes. For example, if code inserts zero into lane 3 before an integer vector addition, but subsequently consumes only lanes 0 through 2, the insertion is unnecessary:
; Before
ins v0.s[3], wzr
add v16.4s, v0.4s, v1.4s
; After
add v16.4s, v0.4s, v1.4s
This requires that the remaining operations can safely compute values in the unused lanes.
The compiler also takes advantage of scalar floating-point and NEON values sharing the same physical registers. A broadcast is unnecessary if only the original low lane is used:
#include <arm_neon.h>
float add_low_lane(float a, float b) {
float32x4_t broadcast = vdupq_n_f32(a);
return vgetq_lane_f32(broadcast, 0) + b;
}
The previous DUP followed by a scalar addition becomes simply:
fadd s0, s0, s1
ARM64 NEON per-lane rotations
Two complementary shifts combined with a bitwise OR express a rotation within each vector lane:
#include <arm_neon.h>
uint32x4_t rotate_lanes(uint32x4_t unused, uint32x4_t a) {
return vorrq_u32(vshrq_n_u32(a, 18), vshlq_n_u32(a, 14));
}
The unused parameter puts a in v1, leaving the return register available
for an instruction that updates its destination. Previously, the calculation
used two shifts and an OR:
shl v17.4s, v1.4s, #14
ushr v16.4s, v1.4s, #18
orr v0.16b, v16.16b, v17.16b
MSVC 14.52 can use unsigned shift-right-and-accumulate:
shl v0.4s, v1.4s, #14
usra v0.4s, v1.4s, #18
The two shifted values occupy disjoint bits, so addition gives the same result as OR. When both shifts are 16, swapping the two halfwords in each 32-bit lane performs the whole rotation with one instruction:
rev32 v0.8h, v1.8h
Inlining Improvements
Inlining removes call overhead, but its larger benefit is often exposing optimizations across a function boundary. MSVC 14.52 improves several decisions that previously left useful helper functions out of line. The examples below illustrate the opportunities; they are not minimal reproductions of a missed inline, and small versions may already inline with earlier compilers.
Single-call-site helpers inside force-inline functions
The inliner can give special consideration to eligible functions with a single
call site. Previously, this analysis was disabled while optimizing a
__forceinline root function, even when its helper was explicitly marked
inline.
Consider this call structure:
static inline unsigned mix(unsigned x) {
x ^= x >> 16;
x *= 0x7FEB352Du;
x ^= x >> 15;
return x;
}
__forceinline unsigned bucket(unsigned x) {
return mix(x) & 255u;
}
unsigned lookup_bucket(unsigned x) {
return bucket(x);
}
The __forceinline on bucket does not itself request that mix be inlined.
The improvement allows the single-call-site heuristic to consider a
user-marked inline helper such as mix while optimizing bucket.
The result can expose the helper’s arithmetic together with its caller’s
masking and other surrounding work.
Keeping slightly larger small helpers inline
MSVC 14.52 raises the small-function allowance from 40 to 50 instructions. The motivating NEON shuffle helpers were roughly 48 nodes, just outside the old allowance.
For example, a SIMD abstraction can wrap lane selection in a template:
#include <arm_neon.h>
template<int Lane>
inline float32x4_t broadcast_lane(float32x4_t value) {
return vdupq_laneq_f32(value, Lane);
}
float32x4_t scale_vector(float32x4_t a, float32x4_t b) {
return vmulq_f32(a, broadcast_lane<1>(b));
}
Keeping such wrappers inline exposes the constant lane selection to the SIMD optimizer, allowing opportunities such as the by-element multiply described above. The example is deliberately small; the allowance change matters for larger wrappers whose intermediate representation falls between the old and new limits. These are compiler-internal size estimates, not source-line counts or a new unconditional inlining guarantee.
Accounting for scalar replacement of local aggregates
The inliner now recognizes more calls whose removal can enable scalar replacement of aggregates (SROA) and dead-store elimination. Passing the address of a local struct to a function forces it to have a memory location, such that the entire struct is written to memory in the caller. The called function might use only a few fields of the struct. Inlining exposes the fields that are actually needed, allowing the optimizer to keep those useful values in registers and skip copying the struct to memory.
For example:
#include <stdint.h>
struct Values {
uint64_t a, b, c, d;
};
void adjust(Values* values, uint64_t delta) {
values->a += delta;
values->b += delta;
values->c += delta;
values->d += delta;
}
uint64_t calculate(
uint64_t a, uint64_t c, uint64_t delta) {
Values values = {a, 0, c, 0};
adjust(&values, delta);
return values.a + values.c;
}
Once adjust is inlined, the struct and the updates to its unused b and
d fields can disappear. The useful calculation is equivalent to:
return (a + delta) + (c + delta);
The new heuristic gives a bonus to eligible calls that the normal heuristic would otherwise decline. It combines a summary of the callee’s fixed-offset pointer accesses with caller-side evidence that the argument is a suitable local aggregate. Pointer escapes, variable-offset accesses, and other cases the analysis cannot safely characterize do not receive this benefit.
Pattern-based Optimizations
MSVC 14.52 recognizes additional profitable arithmetic, selection, comparison,
and bitwise-expression patterns. The examples in this section use simplified
x64 assembly for optimized builds with /O2; the reciprocal transformation
additionally requires /fp:fast.
Sharing a reciprocal across repeated divisions
Several divisions by the same floating-point value can share a reciprocal:
void divide_by_common_value(
double a, double b, double c, double divisor, double* out) {
out[0] = a / divisor;
out[1] = b / divisor;
out[2] = c / divisor;
}
Instead of three separate divisions:
divsd xmm0, xmm3
divsd xmm1, xmm3
divsd xmm2, xmm3
the compiler can perform one division followed by three multiplications:
movsd xmm4, QWORD PTR [one]
divsd xmm4, xmm3
mulsd xmm0, xmm4
mulsd xmm1, xmm4
mulsd xmm2, xmm4
This transformation requires /fp:fast. It is cost-based rather than
unconditional: with only a few uses, direct division may be preferable because
introducing a reciprocal adds a temporary and can lengthen live ranges.
More branchless selections on x64
The x64 if-conversion profitability decision now accepts nonzero integer constants in a pattern already supported on ARM64. A small selection such as:
int select_value(int a, int b) {
return a < b ? a + b : 7;
}
might previously use a branch:
lea eax, DWORD PTR [rcx+rdx]
cmp ecx, edx
jl selected_sum
mov eax, 7
selected_sum:
In MSVC 14.52, it instead can select between register values with a conditional move:
cmp ecx, edx
lea eax, DWORD PTR [rcx+rdx]
mov r8d, 7
cmovge eax, r8d
This removes the control-flow branch and its potential misprediction cost.
Collapsing Boolean expressions to XOR
Some multi-operation Boolean expressions compute a simple exclusive OR:
unsigned symmetric_difference(unsigned a, unsigned b) {
return (a | b) & ~(a & b);
}
A literal implementation might use:
mov eax, ecx
or ecx, edx
and eax, edx
not eax
and eax, ecx
Recognizing the identity reduces the sequence to:
xor ecx, edx
mov eax, ecx
Related forms, including XOR combinations of the AND and OR of the same operands, can simplify in the same way.
Reusing equivalent reversed comparisons
Reversing both comparison operands and the condition can express the same test. Recognizing that equivalence avoids computing identical Boolean values independently:
int equivalent_compare_difference(int a, int b) {
const int first = a >= b ? 1 : 0;
const int second = b <= a ? 1 : 0;
return first - second;
}
Instead of:
xor r8d, r8d
cmp edx, ecx
setle r8b
xor eax, eax
cmp ecx, edx
setge al
sub eax, r8d
the entire expression becomes:
xor eax, eax
Canonicalizing the comparison both enables reuse and exposes the constant result of subtracting equal values.
Recognizing equivalent minimum and maximum selections
Two differently written selections can also compute the same minimum or maximum:
int equivalent_max_difference(int a, int b) {
const int first = a > b ? a : b;
const int second = b > a ? b : a;
return first - second;
}
Without recognizing their equivalence, the compiler might emit:
cmp edx, ecx
mov eax, ecx
cmovg eax, edx
cmovl edx, ecx
sub edx, eax
mov eax, edx
Both selections return the same value, so the optimized result is simply:
xor eax, eax
The recognition covers signed minimum and maximum forms with strict or non-strict comparisons, including equivalent results combined with XOR. Besides saving instructions directly, these simplifications reduce temporary values and can expose further opportunities in later optimization passes.
Conclusion
The Microsoft C++ team released many new optimizations in MSVC Build Tools 14.52. We will continue focusing on performance while developing MSVC 14.53. Many thanks to the compiler engineers who implemented the optimizations and helped write sections of this blog post, including Alex Wong, Aman Arora, Chris Pulido, Reka Kovacs, and Swaroop Sridhar.
MSVC Build Tools 14.52 is available as part of Visual Studio 2026. Try it out today and share your feedback on Visual Studio Developer Community.
0 comments
Be the first to start the discussion.