dotnet/roslyn

Conditionnally skip over Add/Sub/Or when used with a ternary and constant zero

Open

#68,050 创建于 2023年5月2日

在 GitHub 查看
 (4 评论) (0 反应) (0 负责人)C# (4,257 fork)batch import
Area-CompilersCode Gen Qualityhelp wanted

仓库指标

Star
 (20,414 star)
PR 合并指标
 (平均合并 6天 17小时) (30 天内合并 256 个 PR)

描述

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

贡献者指南