[llvm-bugs] [Bug 24766] New: logically identical functions do not result in the same IR

via llvm-bugs llvm-bugs at lists.llvm.org
Wed Sep 9 16:52:08 PDT 2015


https://llvm.org/bugs/show_bug.cgi?id=24766

            Bug ID: 24766
           Summary: logically identical functions do not result in the
                    same IR
           Product: libraries
           Version: trunk
          Hardware: PC
                OS: All
            Status: NEW
          Severity: normal
          Priority: P
         Component: Transformation Utilities
          Assignee: unassignedbugs at nondot.org
          Reporter: spatel+llvm at rotateright.com
                CC: llvm-bugs at lists.llvm.org
    Classification: Unclassified

Based on the discussions in bug 22723 and bug 23827, logically identical
functions should result in the same optimized IR and ultimately the same
machine code regardless of how they're coded in the higher-level language. 

The following two C functions are logically equivalent for all possible inputs:

#include <stdbool.h>

bool switchy(char x1, char x2, char condition) {
    bool conditionMet = false;

    switch (condition) {
        case 0: conditionMet = (x1 == x2);
            break;

        case 1: conditionMet = (x1 <= x2);
            break;
    }
    return conditionMet;
}

bool sneaky(char x1, char x2, char condition) {
    bool equals = (x1 == x2);
    bool lessThanOrEquals = (x1 <= x2);
    bool conditionIsEquals = (0 == condition);
    bool conditionIsLessThanOrEquals = (1 == condition);    
    return (equals & conditionIsEquals) | (lessThanOrEquals &
conditionIsLessThanOrEquals);  
}

The optimized IR is quite different though:

define i1 @switchy(i8 %x1, i8 %x2, i8 %condition) {
entry:
  %conv = sext i8 %condition to i32
  switch i32 %conv, label %epilog [
    i32 0, label %sw1
    i32 1, label %sw2
  ]

sw1:
  %cmp1 = icmp eq i8 %x1, %x2
  %frombool1 = zext i1 %cmp1 to i8
  br label %epilog

sw2:
  %cmp2 = icmp sle i8 %x1, %x2
  %frombool2 = zext i1 %cmp2 to i8
  br label %epilog

epilog:
  %conditionMet = phi i8 [ 0, %entry ], [ %frombool2, %sw2 ], [ %frombool1,
%sw1 ]
  %tobool = icmp ne i8 %conditionMet, 0
  ret i1 %tobool
}

define i1 @sneaky(i8 %x1, i8 %x2, i8 %condition) {
  %cmp1 = icmp eq i8 %x1, %x2
  %cmp2 = icmp sle i8 %x1, %x2
  %cmp3 = icmp eq i8 %condition, 0
  %cmp4 = icmp eq i8 %condition, 1
  %and1 = and i1 %cmp1, %cmp3
  %and2 = and i1 %cmp2, %cmp4
  %or   = or i1 %and1, %and2
  ret i1 %or
}

---------------------------------------------------------------------------

Which of these, if any, is the optimal/canonical form? And how do we get the
one(s) that aren't into that form?

-- 
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/20150909/fdd9c8a7/attachment.html>


More information about the llvm-bugs mailing list