Conditionnally skip over Add/Sub/Or when used with a ternary and constant zero
#68,050 opened on May 2, 2023
Repository metrics
- Stars
- (20,414 stars)
- PR merge metrics
- (Avg merge 6d 17h) (256 merged PRs in 30d)
Description
When operations + - | (Add, Subtract, Bitwise-Or) are used with a ternary operator, in which one of the expression evaluates to a constant 0, I would expect the IL to just skip over that operation
(suggestion could be expanded to Multiply/Divide by ternary with constant 1, or Bitwise-And with ~0)
Version Used: sdk\7.0.203
Steps to Reproduce:
Here is my test code, with ChatInviteFlags being a [Flags] enum:
var ci = (ChatInviteFlags)int.Parse(Console.ReadLine());
int flags = 1024 |
(ci.HasFlag(ChatInviteFlags.broadcast) ? 32 : 0) |
(ci.HasFlag(ChatInviteFlags.pub) ? 64 : 0) |
(ci.HasFlag(ChatInviteFlags.megagroup) ? 128 : 0);
Console.WriteLine(flags);
Expected Behavior: I would expect the OR operations to be optimized by skipping over them entirely when the ternary conditions are false:
IL_0021: brfalse.s IL_0026
IL_0023: ldc.i4.s 32
IL_0025: or
Actual Behavior: Here is the IL currently generated:
IL_0021: brtrue.s IL_0026
IL_0023: ldc.i4.0
IL_0024: br.s IL_0028
IL_0026: ldc.i4.s 32
IL_0028: or