Issue 235642
Summary [ConstantFolding] `ConstantFoldCastOperand` swaps the ptrtoint/ptrtoaddr mid-type widths, misfolding `ptrtoint (inttoptr C)` when the index width differs from the pointer width
Labels new issue
Assignees
Reporter leidian977
    ### Reproducer

```llvm
target datalayout = "e-p:16:16:16:8"
define i32 @t() {
  ret i32 ptrtoint (ptr inttoptr (i32 43981 to ptr) to i32)   ; 43981 = 0xABCD
}
```

```
$ bin/opt -passes=instcombine -S t.ll | grep ret
  ret i32 205
```

`205` is `0xCD`, i.e. the low **8** bits. The correct result is `43981` (`0xABCD`), the low
**16** bits.

Changing only the datalayout so that the index width equals the pointer width gives the
correct answer, which pins the difference on the index width:

```llvm
target datalayout = "e-p:16:16"
define i32 @t() {
  ret i32 ptrtoint (ptr inttoptr (i32 43981 to ptr) to i32)
}
```
```
$ bin/opt -passes=instcombine -S t.ll | grep ret
  ret i32 43981
```

Same thing at a more realistic (CHERI-shaped) width, `e-p:64:64:64:32`:

```llvm
target datalayout = "e-p:64:64:64:32"
define i128 @t() {
  ret i128 ptrtoint (ptr inttoptr (i128 22701506126076928420178618240011261439 to ptr) to i128)
}
```
```
actual   : ret i128 3931559423            ; 0x00000000ea56d5ff -- low 32 bits
expected : ret i128 13930877916299056639  ; 0xc1546ba7ea56d5ff -- low 64 bits
```
The global-initializer form misfolds identically (`opt -passes=globalopt`), and so does
`-passes='default<O2>'`.

Tested at `cc2acc33a5b22db755c1e98c99862dacb117bf48`.

### Cause

`llvm/lib/Analysis/ConstantFolding.cpp`, in `ConstantFoldCastOperand`:

```cpp
if (CE->getOpcode() == Instruction::IntToPtr) {
  // zext/trunc the inttoptr to pointer/address size.
  Type *MidTy = Opcode == Instruction::PtrToInt
                    ? DL.getAddressType(CE->getType())
                    : DL.getIntPtrType(CE->getType());
  FoldedValue = ConstantFoldIntegerCast(CE->getOperand(0), MidTy,
                                        /*IsSigned=*/false, DL);
}
```

The two arms of the ternary are exchanged:

* `ptrtoint` "converts `value` to integer type `ty2` by interpreting **all the pointer
  representation bits** as an integer" (LangRef, `'ptrtoint .. to'` → Semantics), so it needs
  `getIntPtrType` — `DataLayout::getIntPtrType(Type*)` is documented as "an integer … type
  with size at least as big as that of a **pointer**".
* `ptrtoaddr` "only operates on the **index bits** of the pointer and ignores all other bits"
  and "converts `value` … by interpreting the **lowest index-width** pointer representation
  bits as an integer" (LangRef, `'ptrtoaddr .. to'`), so it needs `getAddressType` —
  `DataLayout::getAddressType(Type*)` is `getIndexType(PtrTy)`.

`git blame` puts those three lines on 3e64db583d112 (`[ConstantFolding] Support ptrtoaddr in
cast folds`, #162480). Before that commit the code was an unconditional
`DL.getIntPtrType(CE->getType())`, which was correct for `ptrtoint` because
`case Instruction::PtrToAddr:` just did `break`. The commit message states the intent as
"For the cast pair fold we just need to use the address type instead" — i.e. the address type
for `ptrtoaddr` — which is the opposite of what the ternary implements.

The bad arm is only reached when `CastInst::isEliminableCastPair` declines the pair (the
short-circuit just above, at `ConstantFolding.cpp:1631`). For `(inttoptr, ptrtoint)` that is
`Instructions.cpp`'s case for `MidSize < SrcSize && MidSize < DstSize`, so the observable
condition is:

```
index width < pointer width   AND   SrcBits > pointer width   AND   DstBits > pointer width
```

I enumerated this shape exhaustively (10 datalayouts × 2 address spaces × {ptrtoint,
ptrtoaddr} × {inttoptr, gep-of-null} inner operands × SrcTy/DstTy in
{i8,i16,i32,i64,i128,i192,i256} × 4 constant literals × 4 entry points = 35840 graded
folds, checking each result against the value the LangRef semantics dictate) and that
condition is exactly necessary and sufficient: 320 folds satisfy it and all 320 are wrong;
no fold outside it is wrong.

### The `ptrtoaddr` arm is swapped too, but it happens to be unobservable

Worth stating explicitly so nobody goes looking for a second bug: `ptrtoaddr` gets
`getIntPtrType`, i.e. a mid-type *wider* than needed, and the `ConstantFoldIntegerCast` to
`DestTy` at the end of the block truncates the extra bits back off. The verifier also pins
`DestTy` to the address width ("PtrToAddr result must be address width"), so the two widths
can never diverge in the result. My sweep found 0 wrong `ptrtoaddr` folds out of 760 graded
ones. Only the `ptrtoint` arm produces a wrong value.

The `gep`-based folds in the same block are correct — they already use
`DL.getIndexTypeSizeInBits`, as the commit message says. 0 wrong folds out of 480 graded.

### Suggested fix

```cpp
Type *MidTy = Opcode == Instruction::PtrToInt
                  ? DL.getIntPtrType(CE->getType())
                  : DL.getAddressType(CE->getType());
```

This restores the pre-#162480 behaviour for `ptrtoint` and implements the intent the commit
message describes for `ptrtoaddr`. (I have not built this — no compiler in my environment —
so please treat it as a proposal. Arithmetically it reproduces the `e-p:64:64` control value
exactly.)

### Test coverage gap

`llvm/test/Transforms/InstCombine/ptrtoaddr.ll` — added/extended by #162480 — already uses a
fat-pointer layout (`pe1:64:64:64:32`), and the review thread on that PR was explicitly
discussing CHERI. But every case in that file uses symbolic operands; there is no
constant-folding case at all, so neither `ptrtoint` nor `ptrtoaddr` folding is covered under
a distinct index width. A constant-fold case in that file plus a `ptrtoint` case under a
fat layout would have caught this.

For what it's worth, no in-tree backend currently emits a datalayout with
`index width < pointer width` (`grep` over `lib/Target` for four-field `p` specs comes up
empty), so this is not a miscompile on a shipping target — but the configuration is
documented in the LangRef (which uses `p1:64:64:64:32` as its own example) and is used by
8 files under `llvm/test/`, so the fold is wrong in a supported and in-tree-tested
configuration.
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to