Issue 244434
Summary [InstCombine] Missed optimization: inlined strcmp("-", s) == 0 is not folded to byte compares, unlike strcmp(s, "-") == 0
Labels new issue
Assignees
Reporter Leo0506
    ```c
#include <string.h>
int is_dash(const char *s)         { return strcmp("-", s) == 0; }  // not simplified
int is_dash_swapped(const char *s) { return strcmp(s, "-") == 0; }  // simplified
```

```llvm
define i1 @src(ptr %s) {
entry:
  %c0 = load i8, ptr %s, align 1
  %z0 = zext i8 %c0 to i32
  %d0 = sub nsw i32 45, %z0
  %is = icmp eq i8 %c0, 45
  br i1 %is, label %second, label %tail

second:
  %p1 = getelementptr inbounds nuw i8, ptr %s, i64 1
  %c1 = load i8, ptr %p1, align 1
  %z1 = zext i8 %c1 to i32
  %d1 = sub nsw i32 0, %z1
  br label %tail

tail:
  %r = phi i32 [ %d0, %entry ], [ %d1, %second ]
  %eq = icmp eq i32 %r, 0
  ret i1 %eq
}

define i1 @tgt(ptr %s) {
entry:
  %c0 = load i8, ptr %s, align 1
  %is = icmp eq i8 %c0, 45
 br i1 %is, label %second, label %tail

second:
  %p1 = getelementptr inbounds nuw i8, ptr %s, i64 1
  %c1 = load i8, ptr %p1, align 1
  %n1 = icmp eq i8 %c1, 0
  br label %tail

tail:
  %eq = phi i1 [ false, %entry ], [ %n1, %second ]
  ret i1 %eq
}
```
Alive2 proof: https://alive2.llvm.org/ce/z/b9ULy9

x86-64 (`-O3`):
```asm
is_dash: is_dash_swapped:
  movzbl (%rdi), %ecx              xorl %eax, %eax
  cmpl   $45, %ecx                 cmpb   $45, (%rdi)
  jne .LBB0_1                   jne    .LBB1_2
  movzbl 1(%rdi), %ecx xorl   %eax, %eax
  jmp    .LBB0_3                   cmpb   $0, 1(%rdi)
.LBB0_1:                           sete   %al
  subl   $45, %ecx .LBB1_2:
.LBB0_3:                           retq
  negl   %ecx
 xorl   %eax, %eax
  testl  %ecx, %ecx
  sete   %al
 retq
```
https://godbolt.org/z/5avYPhG8v
IR after `opt -O3` (left unchanged), and the expected form.


On the edge from `%entry`, `%c0 != 45`, so `45 - zext(%c0) == 0` is known false;
on the other edge `0 - zext(%c1) == 0` is `%c1 == 0`. For `strcmp(s, "-")` the
expansion produces `sub %c0, 45` / `zext %c1` and the icmp is pushed through the
phi; for `sub 45, %z0` / `sub 0, %z1` here it is not.

Found in real code: CMake v4.4.2 (the version built by llvm-opt-benchmark), in its
bundled curl, `Utilities/cmcurl/lib/cookie.c:1483`, function `cookie_output()`:
https://github.com/Kitware/CMake/blob/v4.4.2/Utilities/cmcurl/lib/cookie.c#L1483

_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to