[X86][GISel] Fix carry-in for selectUAddSub. (#199261)
When G_UADDE/G_USUBE was chained off a previous G_UADDE/G_UADDO/
G_USUBE/G_USUBO, selectUAddSub re-materialized EFLAGS.CF from the
previous SETB byte using CMP r, 1. That computes (r - 1) and sets
CF iff r < 1 unsigned, i.e. CF = (r == 0) -- the inverse of the
desired carry. The following ADC/SBB then consumed the wrong CF and
produced an off-by-one upper word; e.g. `add i128 0xFF..FF, 1` under
-global-isel returned hi=0 lo=0 instead of hi=1 lo=0.
Emit NEG r instead: NEG sets CF iff its operand is non-zero, matching
the SETB byte. NEG is a two-address (tied) instruction, so emit it
into a fresh virtual register rather than redefining the carry-in
vreg.
C reproducer (compile on x86_64-linux-gnu and run):
```
// clang -O2 -fglobal-isel repro.c -o repro && ./repro
#include <stdio.h>
__attribute__((noinline))
__int128 add128(__int128 a, __int128 b) { return a + b; }
int main(void) {
__int128 a = (__int128)0xFFFFFFFFFFFFFFFFULL;
__int128 r = add128(a, 1);
unsigned long long lo = r, hi = r >> 64;
printf("hi=0x%llx lo=0x%llx\n", hi, lo);
return (hi == 1 && lo == 0) ? 0 : 1;
}
```
Without -fglobal-isel: prints "hi=0x1 lo=0x0", exits 0.
With -fglobal-isel: prints "hi=0x0 lo=0x0", exits 1.
The buggy code-gen emits the inverted-carry sequence (clang trunk,
pre-fix):
```
add128:
movq %rdx, %rax
addq %rdi, %rax
setb %dl
cmpb $1, %dl # CF = (dl == 0), inverse of intended
adcq %rsi, %rcx
movq %rcx, %rdx
retq
```
This bug was found by a large run of Opus 4.7 looking for bugs in
LLVM.Welcome to the LLVM project!
This repository contains the source code for LLVM, a toolkit for the construction of highly optimized compilers, optimizers, and run-time environments.
The LLVM project has multiple components. The core of the project is itself called “LLVM”. This contains all of the tools, libraries, and header files needed to process intermediate representations and convert them into object files. Tools include an assembler, disassembler, bitcode analyzer, and bitcode optimizer.
C-like languages use the Clang frontend. This component compiles C, C++, Objective-C, and Objective-C++ code into LLVM bitcode -- and from there into object files, using LLVM.
Other components include: the libc++ C++ standard library, the LLD linker, and more.
Consult the Getting Started with LLVM page for information on building and running LLVM.
For information on how to contribute to the LLVM project, please take a look at the Contributing to LLVM guide.
Join the LLVM Discourse forums, Discord chat, LLVM Office Hours or Regular sync-ups.
The LLVM project has adopted a code of conduct for participants to all modes of communication within the project.