<table border="1" cellspacing="0" cellpadding="8">
    <tr>
        <th>Issue</th>
        <td>
            <a href=https://github.com/llvm/llvm-project/issues/108511>108511</a>
        </td>
    </tr>

    <tr>
        <th>Summary</th>
        <td>
            Bad x86 codegen for globals access with -fPIE
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            backend:X86,
            llvm:codegen
      </td>
    </tr>

    <tr>
      <th>Assignees</th>
      <td>
      </td>
    </tr>

    <tr>
      <th>Reporter</th>
      <td>
          melver
      </td>
    </tr>
</table>

<pre>
    Consider this input TU:
```
// test.cc
extern int var;

void foo() {
  var++;
}
```

With Clang (trunk) and -fPIE:
```
% clang++ -O2 -fPIE -S -o - test.cc
...
_Z3foov: # @_Z3foov
        .cfi_startproc
# %bb.0:
        movq var@GOTPCREL(%rip), %rax
        incl    (%rax)
 retq
```

Notice the `movq    var@GOTPCREL(%rip), %rax`.

With GCC (13.2):
```
% g++ -O2 -fPIE -S -o - test.cc
...
_Z3foov:
.LFB0:
        .cfi_startproc
 addl    $1, var(%rip)
        ret
 .cfi_endproc
```

GCC correctly produces the more optimal `addl $1, var(%rip)`.

It appears that Clang's -fPIE simply reverts to -fPIC:
```
% clang++ -O2 -fPIC -S -o - test.cc
...
_Z3foov: # @_Z3foov
        .cfi_startproc
# %bb.0:
 movq    var@GOTPCREL(%rip), %rax
        incl    (%rax)
 retq
```

Which is also roughly what GCC produces with -fPIC.

And by default Clang seems to produce similarly bad code:
```
% clang++ -O2 -S -o - test.cc
...
_Z3foov: # @_Z3foov
        .cfi_startproc
# %bb.0:
 movq    var@GOTPCREL(%rip), %rax
        incl    (%rax)
 retq
```
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJzclc2O2zYQx5-GugwsUKRlWwcdbO86CBA0QZsiRS8BRY4sNpSokJSzfvuClHa722yCblH0EEOQrOF8_v4DSHivzwNiTcoDKW8yMYXOurpHc0GXNVZd66MdvFboIHTagx7GKcD7XwnfE3pD6J5s6HLNr-xE2AkC-pBLOdvwLqAbQA8BLsIRflhc0_1itYLWWsJ2hFVAtsspJF92iNdDxPbm-aLp_kGHDo5GDGcgbBfcNHyKGcWgYNW-e3377ZZLkDFsrgart2wOgNUvsLKwejpNnufzn4-_89baC-F7IIwDWdN7yzLA_Mtlqz_6IFwYnZX3JTkQVjZNTh-6uvfv7eVzmn1NX719_-748-2bxKZ0eiSsIuwYQ524exqmB2nic_EVd9F39nAYPn-H2082aIkQOgSyoak8wD_rYEPzrxR4dYzHu4LnLDp_B_q_B74cvDkdvub3HG8QSi101kXsP-3Wo5GeZHAYFkPKhYN6pNxzBOPI0jqHMpgrjM6qSaJPRHvrEOwYdC9MxJsa-VYXf8P5OoAYRxQuphJh3m3Ctn6h5XU_mis4vKALHoJN9uNL9_z4P-_5izbsP9rxD52WHWgPwngLzk7nzlzhS6QaxXuQ7Evc4ATliRL7QUFzBYWtmMwiBHjEPlFfoqMe2ghnrtAIBdIqfJEUP6QImaq5qnglMqyLLduwomQlzbp6Q_mu3UgWT0vZiFJt27KqZCm2vMBtlemaUbamVcHprlgXNK9KJVqBSHlTcdk2ZE2xF9rkxlz63Lpzpr2fsC7oriyKzIgGjU8fNsYaIT_hoAjf_7bbEMYIOxLGYiDh-6jUGYdoLm8yV0fzqpnOnqyp0T74vyoEHQzWB6HgbreBJRBa6-BsbCOMByEl-keLdJtNztRdCKOP9NPn8axDNzW5tD1hp9TE_FiNzv6BMhB2SqN4wk7LNJea_RkAAP__PjoWBQ">