-
-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathDeclarationsProvider.cs
More file actions
324 lines (292 loc) · 15 KB
/
DeclarationsProvider.cs
File metadata and controls
324 lines (292 loc) · 15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Engines;
using BenchmarkDotNet.Environments;
using BenchmarkDotNet.Extensions;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Running;
using Perfolizer.Horology;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace BenchmarkDotNet.Code
{
internal abstract class DeclarationsProvider(BenchmarkCase benchmark)
{
protected static readonly string CoreReturnType = typeof(ValueTask<ClockSpan>).GetCorrectCSharpTypeName();
protected static readonly string CoreParameters = $"long invokeCount, {typeof(IClock).GetCorrectCSharpTypeName()} clock";
protected static readonly string StartClockSyncCode = $"{typeof(StartedClock).GetCorrectCSharpTypeName()} startedClock = {typeof(ClockExtensions).GetCorrectCSharpTypeName()}.Start(clock);";
protected static readonly string ReturnSyncCode = $"return new {CoreReturnType}(startedClock.GetElapsed());";
private static readonly string ReturnCompletedValueTask = $"return new {typeof(ValueTask).GetCorrectCSharpTypeName()}();";
protected BenchmarkCase Benchmark { get; } = benchmark;
protected Descriptor Descriptor => Benchmark.Descriptor;
public abstract string[] GetExtraFields();
public SmartStringBuilder ReplaceTemplate(SmartStringBuilder smartStringBuilder)
{
Replace(smartStringBuilder, Descriptor.GlobalSetupMethod, "$GlobalSetupModifiers$", "$GlobalSetupImpl$", false);
Replace(smartStringBuilder, Descriptor.GlobalCleanupMethod, "$GlobalCleanupModifiers$", "$GlobalCleanupImpl$", true);
Replace(smartStringBuilder, Descriptor.IterationSetupMethod, "$IterationSetupModifiers$", "$IterationSetupImpl$", false);
Replace(smartStringBuilder, Descriptor.IterationCleanupMethod, "$IterationCleanupModifiers$", "$IterationCleanupImpl$", false);
return ReplaceCore(smartStringBuilder)
.Replace("$DisassemblerEntryMethodImpl$", GetWorkloadMethodCall(GetPassArgumentsDirect()))
.Replace("$OperationsPerInvoke$", Descriptor.OperationsPerInvoke.ToString())
.Replace("$WorkloadTypeName$", Descriptor.Type.GetCorrectCSharpTypeName());
}
private void Replace(SmartStringBuilder smartStringBuilder, MethodInfo? method, string replaceModifiers, string replaceImpl, bool isGlobalCleanup)
{
string modifier;
string impl;
if (method == null)
{
modifier = string.Empty;
impl = ReturnCompletedValueTask;
if (isGlobalCleanup)
{
impl = PrependExtraGlobalCleanupImpl(impl);
}
smartStringBuilder
.Replace(replaceModifiers, modifier)
.Replace(replaceImpl, impl);
return;
}
if (method.ReturnType.IsAwaitable())
{
modifier = "async";
impl = $"await {GetMethodPrefix(method)}.{method.Name}();";
}
else
{
modifier = string.Empty;
impl = $"""
{GetMethodPrefix(method)}.{method.Name}();
{ReturnCompletedValueTask}
""";
}
if (isGlobalCleanup)
{
impl = PrependExtraGlobalCleanupImpl(impl);
}
smartStringBuilder
.Replace(replaceModifiers, modifier)
.Replace(replaceImpl, impl);
}
protected abstract string PrependExtraGlobalCleanupImpl(string impl);
protected abstract SmartStringBuilder ReplaceCore(SmartStringBuilder smartStringBuilder);
private static string GetMethodPrefix(MethodInfo method)
=> method.IsStatic ? method.DeclaringType!.GetCorrectCSharpTypeName() : "base";
protected string GetWorkloadMethodCall(string passArguments)
=> $"{GetMethodPrefix(Descriptor.WorkloadMethod)}.{Descriptor.WorkloadMethod.Name}({passArguments});";
protected string GetPassArgumentsDirect()
=> string.Join(
", ",
Descriptor.WorkloadMethod.GetParameters()
.Select((parameter, index) => $"{CodeGenerator.GetParameterModifier(parameter)} this.__fieldsContainer.argField{index}")
);
}
internal class SyncDeclarationsProvider(BenchmarkCase benchmark) : DeclarationsProvider(benchmark)
{
public override string[] GetExtraFields() => [];
protected override string PrependExtraGlobalCleanupImpl(string impl) => impl;
protected override SmartStringBuilder ReplaceCore(SmartStringBuilder smartStringBuilder)
{
string loadArguments = GetLoadArguments();
string passArguments = GetPassArguments();
string workloadMethodCall = GetWorkloadMethodCall(passArguments);
string coreImpl = $$"""
private unsafe {{CoreReturnType}} OverheadActionUnroll({{CoreParameters}})
{
{{loadArguments}}
{{StartClockSyncCode}}
while (--invokeCount >= 0)
{
this.__Overhead({{passArguments}});@Unroll@
}
{{ReturnSyncCode}}
}
private unsafe {{CoreReturnType}} OverheadActionNoUnroll({{CoreParameters}})
{
{{loadArguments}}
{{StartClockSyncCode}}
while (--invokeCount >= 0)
{
this.__Overhead({{passArguments}});
}
{{ReturnSyncCode}}
}
private unsafe {{CoreReturnType}} WorkloadActionUnroll({{CoreParameters}})
{
{{loadArguments}}
{{StartClockSyncCode}}
while (--invokeCount >= 0)
{
{{workloadMethodCall}}@Unroll@
}
{{ReturnSyncCode}}
}
private unsafe {{CoreReturnType}} WorkloadActionNoUnroll({{CoreParameters}})
{
{{loadArguments}}
{{StartClockSyncCode}}
while (--invokeCount >= 0)
{
{{workloadMethodCall}}
}
{{ReturnSyncCode}}
}
""";
return smartStringBuilder
.Replace("$CoreImpl$", coreImpl);
}
private string GetLoadArguments()
=> string.Join(
Environment.NewLine,
Descriptor.WorkloadMethod.GetParameters()
.Select((parameter, index) =>
{
var refModifier = parameter.ParameterType.IsByRef ? "ref" : string.Empty;
return $"{refModifier} {parameter.ParameterType.GetCorrectCSharpTypeName()} arg{index} = {refModifier} this.__fieldsContainer.argField{index};";
})
);
private string GetPassArguments()
=> string.Join(
", ",
Descriptor.WorkloadMethod.GetParameters()
.Select((parameter, index) => $"{CodeGenerator.GetParameterModifier(parameter)} arg{index}")
);
}
internal class AsyncDeclarationsProvider(BenchmarkCase benchmark) : DeclarationsProvider(benchmark)
{
public override string[] GetExtraFields() =>
[
$"public {typeof(WorkloadValueTaskSource).GetCorrectCSharpTypeName()} workloadContinuerAndValueTaskSource;",
$"public {typeof(IClock).GetCorrectCSharpTypeName()} clock;",
"public long invokeCount;"
];
protected override string PrependExtraGlobalCleanupImpl(string impl)
=> $"""
this.__fieldsContainer.workloadContinuerAndValueTaskSource?.Complete();
{impl}
""";
protected override SmartStringBuilder ReplaceCore(SmartStringBuilder smartStringBuilder)
{
// Unlike sync calls, async calls suffer from unrolling, so we multiply the invokeCount by the unroll factor and delegate the implementation to *NoUnroll methods.
int unrollFactor = Benchmark.Job.ResolveValue(RunMode.UnrollFactorCharacteristic, EnvironmentResolver.Instance);
string passArguments = GetPassArgumentsDirect();
string workloadMethodCall = GetWorkloadMethodCall(passArguments);
bool hasAsyncMethodBuilderAttribute = TryGetAsyncMethodBuilderAttribute(out var asyncMethodBuilderAttribute);
Type workloadCoreReturnType = GetWorkloadCoreReturnType(hasAsyncMethodBuilderAttribute);
string finalReturn = GetFinalReturn(workloadCoreReturnType);
string coreImpl = $$"""
private {{CoreReturnType}} OverheadActionUnroll({{CoreParameters}})
{
return this.OverheadActionNoUnroll(invokeCount * {{unrollFactor}}, clock);
}
private {{CoreReturnType}} OverheadActionNoUnroll({{CoreParameters}})
{
{{StartClockSyncCode}}
while (--invokeCount >= 0)
{
this.__Overhead({{passArguments}});
}
{{ReturnSyncCode}}
}
private {{CoreReturnType}} WorkloadActionUnroll({{CoreParameters}})
{
return this.WorkloadActionNoUnroll(invokeCount * {{unrollFactor}}, clock);
}
private {{CoreReturnType}} WorkloadActionNoUnroll({{CoreParameters}})
{
this.__fieldsContainer.invokeCount = invokeCount;
this.__fieldsContainer.clock = clock;
if (this.__fieldsContainer.workloadContinuerAndValueTaskSource == null)
{
this.__fieldsContainer.workloadContinuerAndValueTaskSource = new {{typeof(WorkloadValueTaskSource).GetCorrectCSharpTypeName()}}();
this.__StartWorkload();
}
return this.__fieldsContainer.workloadContinuerAndValueTaskSource.Continue();
}
private async void __StartWorkload()
{
await __WorkloadCore();
}
{{asyncMethodBuilderAttribute}}
private async {{workloadCoreReturnType.GetCorrectCSharpTypeName()}} __WorkloadCore()
{
try
{
if (await this.__fieldsContainer.workloadContinuerAndValueTaskSource.GetIsComplete())
{
{{finalReturn}}
}
while (true)
{
{{typeof(StartedClock).GetCorrectCSharpTypeName()}} startedClock = {{typeof(ClockExtensions).GetCorrectCSharpTypeName()}}.Start(this.__fieldsContainer.clock);
while (--this.__fieldsContainer.invokeCount >= 0)
{
// Necessary because of error CS4004: Cannot await in an unsafe context
{{Descriptor.WorkloadMethod.ReturnType.GetCorrectCSharpTypeName()}} awaitable;
unsafe { awaitable = {{workloadMethodCall}} }
await awaitable;
}
if (await this.__fieldsContainer.workloadContinuerAndValueTaskSource.SetResultAndGetIsComplete(startedClock.GetElapsed()))
{
{{finalReturn}}
}
}
}
catch (global::System.Exception e)
{
__fieldsContainer.workloadContinuerAndValueTaskSource.SetException(e);
{{finalReturn}}
}
}
""";
return smartStringBuilder
.Replace("$CoreImpl$", coreImpl);
}
private bool TryGetAsyncMethodBuilderAttribute(out string asyncMethodBuilderAttribute)
{
asyncMethodBuilderAttribute = string.Empty;
if (Descriptor.WorkloadMethod.HasAttribute<AsyncCallerTypeAttribute>())
{
return false;
}
if (Descriptor.WorkloadMethod.GetAsyncMethodBuilderAttribute() is not { } attr)
{
return false;
}
if (attr.GetType().GetProperty(nameof(AsyncMethodBuilderAttribute.BuilderType), BindingFlags.Public | BindingFlags.Instance)?.GetValue(attr) is not Type builderType)
{
return false;
}
asyncMethodBuilderAttribute = $"[{typeof(AsyncMethodBuilderAttribute).GetCorrectCSharpTypeName()}(typeof({builderType.GetCorrectCSharpTypeName()}))]";
return true;
}
private Type GetWorkloadCoreReturnType(bool hasAsyncMethodBuilderAttribute)
{
if (Descriptor.WorkloadMethod.ResolveAttribute<AsyncCallerTypeAttribute>() is { } asyncCallerTypeAttribute)
{
return asyncCallerTypeAttribute.AsyncCallerType;
}
if (hasAsyncMethodBuilderAttribute
|| Descriptor.WorkloadMethod.ReturnType.HasAsyncMethodBuilderAttribute()
// Task and Task<T> are not annotated with their builder type, the C# compiler special-cases them.
|| (Descriptor.WorkloadMethod.ReturnType.IsGenericType && Descriptor.WorkloadMethod.ReturnType.GetGenericTypeDefinition() == typeof(Task<>))
)
{
return Descriptor.WorkloadMethod.ReturnType;
}
// Fallback to Task if the benchmark return type is Task or any awaitable type that is not a custom task-like type.
return typeof(Task);
}
private static string GetFinalReturn(Type workloadCoreReturnType)
{
var finalReturnType = workloadCoreReturnType
.GetMethod(nameof(Task.GetAwaiter), BindingFlags.Public | BindingFlags.Instance)!
.ReturnType!
.GetMethod(nameof(TaskAwaiter.GetResult))!
.ReturnType;
return finalReturnType == typeof(void)
? "return;"
: $"return default({finalReturnType.GetCorrectCSharpTypeName()});";
}
}
}