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

    <tr>
        <th>Summary</th>
        <td>
            [SelectionDAG] Incorrect handling of lifetimes with multiple objects
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            llvm:codegen,
            miscompilation,
            llvm:SelectionDAG
      </td>
    </tr>

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

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

<pre>
    The lowering in https://github.com/llvm/llvm-project/blob/0cc6b464f8adb739e6f9bcc9bda8cff9bb1f1c2a/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp#L7554-L7555 treats lifetime.start/end on an argument that has multiple underlying objects by performing a lifetime start/end on *each* of the objects.

So if you have something like this:
```llvm
define i64 @test(i1 %c, ptr %p) {
 %a = alloca i64
  %b = alloca i64
  %sel.b = select i1 %c, ptr %b, ptr %a
  call void @llvm.lifetime.start(i64 8, ptr %a)
  store i64 1, ptr %a
  call void @llvm.lifetime.end(i64 8, ptr %sel.b)
  call void @llvm.lifetime.start(i64 8, ptr %b)
  store i64 2, ptr %b
  store ptr %b, ptr %p ; prevent store from being optimized away
  %v = load i64, ptr %a
  call void @llvm.lifetime.end(i64 8, ptr %b)
  ret i64 %v
}
```
Then the lifetime.end on `%sel.b` will be lowered to a lifetime.end on *both* `%a` and `%b`. However, assuming `%c` is true at runtime, it only ends the lifetime of `%b` and the overall IR is well-defined.

The final assembly is incorrect as a result of stack coloring:
```asm
        movq    $1, -8(%rsp)
        movq    $2, -8(%rsp)
        leaq    -8(%rsp), %rax
        movq    %rax, (%rsi)
        movq    -8(%rsp), %rax
        retq
```

</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJysVdtu4zYQ_Rr6ZRBDoi6WHvTgxPB2gT519wd4GVlsKFJLUnbdry9IOY6duC22KBA4ImfmcD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