[llvm-bugs] [Bug 51285] New: LLVM optimization and code generation for if-else chains vs ternary chains vs a switch
via llvm-bugs
llvm-bugs at lists.llvm.org
Fri Jul 30 16:50:40 PDT 2021
https://bugs.llvm.org/show_bug.cgi?id=51285
Bug ID: 51285
Summary: LLVM optimization and code generation for if-else
chains vs ternary chains vs a switch
Product: tools
Version: trunk
Hardware: PC
OS: Windows NT
Status: NEW
Severity: enhancement
Priority: P
Component: opt
Assignee: unassignedbugs at nondot.org
Reporter: llvm at rifkin.dev
CC: llvm-bugs at lists.llvm.org
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: https://godbolt.org/z/3PE59hKdx.
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).
--
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/20210730/af0363f8/attachment.html>
More information about the llvm-bugs
mailing list