Skip to content

Commit b50ab6f

Browse files
authored
Fold RuntimeInformation.IsOSPlatform / OperatingSystem.IsOSPlatform in ILLink (#133128)
1 parent d717724 commit b50ab6f

4 files changed

Lines changed: 186 additions & 0 deletions

File tree

‎src/coreclr/tools/ILTrim.Tests/ILTrimExpectedFailures.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -463,6 +463,7 @@ UnreachableBlock.MethodArgumentPropagation
463463
UnreachableBlock.MethodWithParametersSubstitutions
464464
UnreachableBlock.MultiStageRemoval
465465
UnreachableBlock.NestedFinallyInFinallyHandler
466+
UnreachableBlock.OSPlatformGuard
466467
UnreachableBlock.ReplacedJumpTarget
467468
UnreachableBlock.ReplacedReturns
468469
UnreachableBlock.ResultInliningNotPossible

‎src/tools/illink/src/linker/Linker.Steps/UnreachableBlocksOptimizer.cs‎

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -898,6 +898,83 @@ public bool RewriteBody()
898898
return true;
899899
}
900900

901+
// Recognizes the OS platform-guard idiom and evaluates it to a constant. Unlike the
902+
// OperatingSystem.IsX() predicates (per-target literals the generic analyzer already folds),
903+
// IsOSPlatform routes through an instance String.Equals and, for the RuntimeInformation
904+
// overload, an opaque OSPlatform struct, so it needs direct handling. The recognized platform
905+
// token is mapped to its OperatingSystem.IsX() predicate, which is then folded normally -- that
906+
// predicate also encodes the OSX/MacCatalyst aliasing, so no manual replication is needed.
907+
bool TryEvaluateOSPlatformGuard(in UnreachableBlocksOptimizer optimizer, MethodDefinition md, Collection<Instruction> instructions, int callIndex, [NotNullWhen(true)] out Instruction? result)
908+
{
909+
result = null;
910+
911+
if (md.Name != "IsOSPlatform" || !md.IsStatic || md.GetMetadataParametersCount() != 1 || callIndex < 1)
912+
return false;
913+
914+
bool isRuntimeInformation = md.DeclaringType.IsTypeOf("System.Runtime.InteropServices", "RuntimeInformation");
915+
bool isOperatingSystem = md.DeclaringType.IsTypeOf("System", "OperatingSystem");
916+
if (!isRuntimeInformation && !isOperatingSystem)
917+
return false;
918+
919+
Instruction argProducer = instructions[callIndex - 1];
920+
string? token;
921+
922+
if (isOperatingSystem)
923+
{
924+
// OperatingSystem.IsOSPlatform(string) with a literal platform name.
925+
token = argProducer.OpCode.Code == Code.Ldstr ? (string)argProducer.Operand : null;
926+
}
927+
else
928+
{
929+
// RuntimeInformation.IsOSPlatform(OSPlatform) built from a well-known OSPlatform value.
930+
if (argProducer.OpCode.Code != Code.Call)
931+
return false;
932+
933+
MethodDefinition? producer = context.TryResolve((MethodReference)argProducer.Operand);
934+
if (producer == null || !producer.DeclaringType.IsTypeOf("System.Runtime.InteropServices", "OSPlatform"))
935+
return false;
936+
937+
token = producer.Name switch
938+
{
939+
"get_Windows" => "WINDOWS",
940+
"get_Linux" => "LINUX",
941+
"get_OSX" => "OSX",
942+
"get_FreeBSD" => "FREEBSD",
943+
"Create" when callIndex >= 2 && instructions[callIndex - 2].OpCode.Code == Code.Ldstr
944+
=> (string)instructions[callIndex - 2].Operand,
945+
_ => null,
946+
};
947+
}
948+
949+
string? predicate = token?.ToUpperInvariant() switch
950+
{
951+
"WINDOWS" => "IsWindows",
952+
"LINUX" => "IsLinux",
953+
"OSX" or "MACOS" => "IsMacOS",
954+
"BROWSER" => "IsBrowser",
955+
"WASI" => "IsWasi",
956+
"ANDROID" => "IsAndroid",
957+
"IOS" => "IsIOS",
958+
"MACCATALYST" => "IsMacCatalyst",
959+
"TVOS" => "IsTvOS",
960+
"WATCHOS" => "IsWatchOS",
961+
"FREEBSD" => "IsFreeBSD",
962+
_ => null, // unknown/custom platform: leave the guard untouched
963+
};
964+
if (predicate == null)
965+
return false;
966+
967+
TypeDefinition? operatingSystem = md.DeclaringType.Module.GetType("System.OperatingSystem");
968+
MethodDefinition? isPlatform = operatingSystem?.Methods.FirstOrDefault(
969+
m => m.Name == predicate && m.IsStatic && m.HasBody && m.GetMetadataParametersCount() == 0);
970+
if (isPlatform == null)
971+
return false;
972+
973+
// The predicate body is a per-target 'return true/false', which the constant analyzer folds.
974+
result = optimizer.TryGetMethodCallResult(new CalleePayload(isPlatform, Array.Empty<Instruction>()))?.Instruction;
975+
return result != null;
976+
}
977+
901978
public bool ApplyTemporaryInlining(in UnreachableBlocksOptimizer optimizer)
902979
{
903980
bool changed = false;
@@ -920,6 +997,19 @@ public bool ApplyTemporaryInlining(in UnreachableBlocksOptimizer optimizer)
920997
if (md.IsVirtual || md.CallingConvention == MethodCallingConvention.VarArg)
921998
break;
922999

1000+
// RuntimeInformation.IsOSPlatform(OSPlatform.X) / OperatingSystem.IsOSPlatform("X")
1001+
// don't fold through the generic constant analyzer (the argument flows through an
1002+
// opaque OSPlatform struct or an instance String.Equals). Recognize the guard idiom
1003+
// directly so its dead branch (and any foreign P/Invoke it protects) can be trimmed.
1004+
if (context.IsOptimizationEnabled(CodeOptimizations.IPConstantPropagation, Body.Method)
1005+
&& TryEvaluateOSPlatformGuard(optimizer, md, instructions, i, out Instruction? osGuardResult))
1006+
{
1007+
RewriteToNop(i - 1, 1);
1008+
Rewrite(i, osGuardResult);
1009+
changed = true;
1010+
break;
1011+
}
1012+
9231013
Instruction[]? args = GetArgumentsOnStack(md, FoldedInstructions ?? instructions, i);
9241014
targetResult = args?.Length > 0 && md.IsStatic ? EvaluateIntrinsicCall(md, args) : null;
9251015

‎src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/UnreachableBlockTests.g.cs‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,12 @@ public Task MultiStageRemoval()
6767
return RunTest(allowMissingWarnings: true);
6868
}
6969

70+
[Fact]
71+
public Task OSPlatformGuard()
72+
{
73+
return RunTest(allowMissingWarnings: true);
74+
}
75+
7076
[Fact]
7177
public Task ReplacedJumpTarget()
7278
{
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
using System.Runtime.InteropServices;
2+
using Mono.Linker.Tests.Cases.Expectations.Assertions;
3+
using Mono.Linker.Tests.Cases.Expectations.Metadata;
4+
5+
namespace Mono.Linker.Tests.Cases.UnreachableBlock
6+
{
7+
[SetupCSharpCompilerToUse("csc")]
8+
[SetupCompileArgument("/optimize+")]
9+
[SetupLinkerArgument("--enable-opt", "ipconstprop")]
10+
public class OSPlatformGuard
11+
{
12+
public static void Main()
13+
{
14+
TestRuntimeInformationIsOSPlatform();
15+
TestRuntimeInformationCreate();
16+
TestOperatingSystemIsOSPlatform();
17+
18+
// Keep every branch target reachable independently so their retention is platform-independent.
19+
// The guards above are still folded to a constant, asserted via ExpectBodyModified (without the
20+
// platform-guard folding IsOSPlatform never folds and the bodies would be unchanged).
21+
Windows();
22+
NotWindows();
23+
Linux();
24+
NotLinux();
25+
FreeBSD();
26+
NotFreeBSD();
27+
}
28+
29+
[Kept]
30+
[ExpectBodyModified]
31+
static void TestRuntimeInformationIsOSPlatform()
32+
{
33+
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
34+
Windows();
35+
else
36+
NotWindows();
37+
}
38+
39+
[Kept]
40+
[ExpectBodyModified]
41+
static void TestRuntimeInformationCreate()
42+
{
43+
if (RuntimeInformation.IsOSPlatform(OSPlatform.Create("FREEBSD")))
44+
FreeBSD();
45+
else
46+
NotFreeBSD();
47+
}
48+
49+
[Kept]
50+
[ExpectBodyModified]
51+
static void TestOperatingSystemIsOSPlatform()
52+
{
53+
if (System.OperatingSystem.IsOSPlatform("Linux"))
54+
Linux();
55+
else
56+
NotLinux();
57+
}
58+
59+
[Kept]
60+
static void Windows()
61+
{
62+
}
63+
64+
[Kept]
65+
static void NotWindows()
66+
{
67+
}
68+
69+
[Kept]
70+
static void Linux()
71+
{
72+
}
73+
74+
[Kept]
75+
static void NotLinux()
76+
{
77+
}
78+
79+
[Kept]
80+
static void FreeBSD()
81+
{
82+
}
83+
84+
[Kept]
85+
static void NotFreeBSD()
86+
{
87+
}
88+
}
89+
}

0 commit comments

Comments
 (0)