[llvm-bugs] [Bug 44374] New: Wrong optimizations for pointers: `p == q ? p : q` -> `q`

via llvm-bugs llvm-bugs at lists.llvm.org
Tue Dec 24 08:47:52 PST 2019


            Bug ID: 44374
           Summary: Wrong optimizations for pointers: `p == q ? p : q` ->
           Product: new-bugs
           Version: trunk
          Hardware: PC
                OS: Linux
            Status: NEW
          Severity: normal
          Priority: P
         Component: new bugs
          Assignee: unassignedbugs at nondot.org
          Reporter: ch3root at openwall.com
                CC: htmldeveloper at gmail.com, llvm-bugs at lists.llvm.org

Similar to bug 44313.

The optimizer sometimes changes `p == q ? p : q` to `q`. This is wrong when the
actual provenance of `p` differs from that of `q`.
There are two forms -- with the actual conditional operator and with the `if`

The ideal example would be constructed with the help of restricted pointers but
it's run into a theoretical problem -- see the first testcase in bug 44373.
My other examples require two conditionals to eliminate the possibility of UB.
Comparison of integers should give stable results, hopefully that would be
enough to demonstrate the problem.

gcc bug -- https://gcc.gnu.org/bugzilla/show_bug.cgi?id=93052.

Example with the conditional operator and with dead malloc (the wrong
optimization seems to be applied in Early CSE):

#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>

__attribute__((noipa,optnone)) // imagine it in a separate TU
static void *opaque(void *p) { return p; }

int main()
    int *q = malloc(sizeof(int));
    uintptr_t iq = (uintptr_t)(void *)q;

    int *p = malloc(sizeof(int));
    uintptr_t ip = (uintptr_t)(void *)p;

    uintptr_t ir = ip == iq ? ip : iq;
    if (ip == iq) {
        *p = 1;
        *(int *)(void *)ir = 2;
        printf("result: %d\n", *p);
$ clang -std=c11 -Weverything -Wno-unknown-attributes test.c && ./a.out
result: 2
$ clang -std=c11 -Weverything -Wno-unknown-attributes -O3 test.c && ./a.out
result: 1
clang x86-64 version: clang version 10.0.0

The idea of problems arising from `p == q ? p : q` is from Chung-Kil Hur via

You are receiving this mail because:
You are on the CC list for the bug.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-bugs/attachments/20191224/6d3934c4/attachment.html>

More information about the llvm-bugs mailing list