<html>
<head>
<base href="https://bugs.llvm.org/">
</head>
<body><table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Bug ID</th>
<td><a class="bz_bug_link
bz_status_NEW "
title="NEW - LLVM optimization and code generation for if-else chains vs ternary chains vs a switch"
href="https://bugs.llvm.org/show_bug.cgi?id=51285">51285</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>LLVM optimization and code generation for if-else chains vs ternary chains vs a switch
</td>
</tr>
<tr>
<th>Product</th>
<td>tools
</td>
</tr>
<tr>
<th>Version</th>
<td>trunk
</td>
</tr>
<tr>
<th>Hardware</th>
<td>PC
</td>
</tr>
<tr>
<th>OS</th>
<td>Windows NT
</td>
</tr>
<tr>
<th>Status</th>
<td>NEW
</td>
</tr>
<tr>
<th>Severity</th>
<td>enhancement
</td>
</tr>
<tr>
<th>Priority</th>
<td>P
</td>
</tr>
<tr>
<th>Component</th>
<td>opt
</td>
</tr>
<tr>
<th>Assignee</th>
<td>unassignedbugs@nondot.org
</td>
</tr>
<tr>
<th>Reporter</th>
<td>llvm@rifkin.dev
</td>
</tr>
<tr>
<th>CC</th>
<td>llvm-bugs@lists.llvm.org
</td>
</tr></table>
<p>
<div>
<pre>I'm looking at an example of three equivalent functions implemented with
if-else chains, ternary chains, and a switch. LLVM is not compiling them
equivalently: <a href="https://godbolt.org/z/3PE59hKdx">https://godbolt.org/z/3PE59hKdx</a>.
For some reason the if-else chain and switch compile equivalently but the
ternary is missing a fold.
I don't think it's idealistic to say these should compile equivalently - if
someone told me to prefer one over the other for performance reasons I'd
dismiss it as a micro-optimization.
GCC struggles with this as well, I've just filed a bug report for GCC.
Interestingly GCC does the ternary and switch well but struggles with the
if-else chain.
As for the ternary case, the switch and if-else chain compile as such:
define dso_local i32 @_Z3fooi(i32 %0) local_unnamed_addr #0 {
; if %0 - 1 < 4 { return %0 } else { return -1 }
%2 = add i32 %0, -1
%3 = icmp ult i32 %2, 4
%4 = select i1 %3, i32 %0, i32 -1
ret i32 %4
}
Whereas the ternary chain compiles as
define dso_local i32 @_Z5func2i(i32 %0) local_unnamed_addr #0 {
; if %0 - 1 < 3 {
; return %0
; } else {
; if %0 == 4 {
; return 4
; } else {
; return -1
; }
; }
%2 = add i32 %0, -1
%3 = icmp ult i32 %2, 3
%4 = icmp eq i32 %0, 4
%5 = select i1 %4, i32 4, i32 -1
%6 = select i1 %3, i32 %0, i32 %5
ret i32 %6
}
Evidently missing a fold.
One last thing to note: clang trunk compiles the ternary chain better than
clang 12 (which has leaves branch in it).</pre>
</div>
</p>
<hr>
<span>You are receiving this mail because:</span>
<ul>
<li>You are on the CC list for the bug.</li>
</ul>
</body>
</html>