-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFunctionTransformPipeline.cs
More file actions
548 lines (419 loc) · 19 KB
/
Copy pathFunctionTransformPipeline.cs
File metadata and controls
548 lines (419 loc) · 19 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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
#pragma warning disable 0162
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using JSIL.Ast;
using JSIL.Internal;
using JSIL.Threading;
using JSIL.Transforms;
using JSIL.Translator;
using Mono.Cecil;
namespace JSIL.Internal {
public delegate bool FunctionTransformPipelineStage ();
public class FunctionTransformPipeline {
public const int SuspendCountLogThreshold = 2;
public const bool CheckForStaticAnalysisChanges = false;
public const bool Trace = false;
public readonly AssemblyTranslator Translator;
public readonly QualifiedMemberIdentifier Identifier;
public readonly JSFunctionExpression Function;
public readonly SpecialIdentifiers SpecialIdentifiers;
public readonly Queue<FunctionTransformPipelineStage> Pipeline = new Queue<FunctionTransformPipelineStage>();
public int SuspendCount = 0;
private FunctionAnalysis2ndPass OriginalSecondPass;
private string OriginalFunctionBody;
public FunctionTransformPipeline (
AssemblyTranslator translator,
QualifiedMemberIdentifier identifier, JSFunctionExpression function,
SpecialIdentifiers si
) {
Translator = translator;
Identifier = identifier;
Function = function;
SpecialIdentifiers = si;
FillPipeline();
if (!Translator.FunctionCache.ActiveTransformPipelines.TryAdd(Identifier, this))
throw new ThreadStateException();
if (CheckForStaticAnalysisChanges) {
OriginalFunctionBody = Function.Body.ToString();
OriginalSecondPass = Translator.FunctionCache.GetSecondPass(function.Method, function.Method.QualifiedIdentifier);
}
}
public TypeSystem TypeSystem {
get {
return SpecialIdentifiers.TypeSystem;
}
}
public MethodTypeFactory MethodTypes {
get {
return Translator.FunctionCache.MethodTypes;
}
}
public IFunctionSource FunctionSource {
get {
return Translator.FunctionCache;
}
}
public Configuration Configuration {
get {
return Translator.Configuration;
}
}
public TypeInfoProvider TypeInfoProvider {
get {
return Translator.TypeInfoProvider;
}
}
private bool RunStaticAnalysisDependentTransform<T> (T visitor, Action<T> postVisitAction = null)
where T : StaticAnalysisJSAstVisitor
{
visitor.Visit(Function);
if (postVisitAction != null)
postVisitAction(visitor);
return true;
}
public void Enqueue (FunctionTransformPipelineStage stage) {
Pipeline.Enqueue(stage);
}
public bool RunUntilCompletion () {
const int lockTimeoutMs = 250;
bool completed = false;
var entry = Translator.FunctionCache.GetCacheEntry(Identifier);
TrackedLockCollection.DeadlockInfo deadlock;
var lockResult = entry.StaticAnalysisDataLock.TryBlockingEnter(out deadlock, timeoutMs: lockTimeoutMs);
if (!lockResult.Success) {
if (deadlock != null)
Console.Error.WriteLine("Failed to lock '{0}' for transform pipeline: {1} {2}", Identifier, lockResult.FailureReason, deadlock);
return false;
}
try {
while (Pipeline.Count > 0) {
var currentStage = Pipeline.Peek();
try {
var stageSucceeded = false;
try {
stageSucceeded = currentStage();
} catch (TemporarilySuspendTransformPipelineException exc) {
if (Trace)
Console.WriteLine(
"Static analysis for '{2}::{3}' suspended due to dependency on '{0}::{1}'",
exc.Identifier.Type.Name, exc.Identifier.Member.Name,
Identifier.Type.Name, Identifier.Member.Name
);
return false;
}
if (stageSucceeded) {
Pipeline.Dequeue();
if (CheckForStaticAnalysisChanges) {
var currentSecondPass = Translator.FunctionCache.GetSecondPass(this.Function.Method, this.Function.Method.QualifiedIdentifier);
string[] differences;
if (!currentSecondPass.Equals(OriginalSecondPass, out differences)) {
var currentFunctionBody = Function.Body.ToString();
Console.WriteLine("// Second pass data changed by pipeline stage '" + currentStage.Method.Name + "' - " + String.Join(", ", differences));
Console.WriteLine("// Original function body //");
Console.WriteLine(OriginalFunctionBody);
Console.WriteLine("// New function body //");
Console.WriteLine(currentFunctionBody);
OriginalSecondPass = currentSecondPass;
OriginalFunctionBody = currentFunctionBody;
}
}
} else {
SuspendCount += 1;
return (completed = false);
}
} catch (Exception exc) {
string functionName;
try {
if ((Function.Method != null) && (Function.Method.Reference != null))
functionName = Function.Method.Reference.FullName;
else
functionName = Function.DisplayName ?? "<unknown>";
} catch {
functionName = "<exception in FullName, yay mono>";
}
throw new FunctionTransformFailureException(functionName, currentStage.Method.Name, exc);
}
}
return (completed = true);
} finally {
entry.TransformPipelineHasCompleted |= completed;
entry.StaticAnalysisDataLock.Exit();
if (completed) {
FunctionTransformPipeline temp;
if (!Translator.FunctionCache.ActiveTransformPipelines.TryRemove(Identifier, out temp))
throw new ThreadStateException();
} else {
if (!Translator.FunctionCache.PendingTransformsQueue.TryEnqueue(Identifier))
throw new ThreadStateException();
}
}
}
private void FillPipeline () {
Enqueue(BuildLabelGroups);
Enqueue(IntroduceVariableDeclarationsAndReferences);
Enqueue(SynthesizePropertySetterReturnValues);
// Important to run this before static analysis. Otherwise var, declaration and ctor
// call can end up split, making a variable appear to get modified.
Enqueue(FixupStructConstructorInvocations);
Enqueue(EliminateTemporaries);
Enqueue(EmulateInt64);
Enqueue(EmulateStructAssignment);
Enqueue(SimplifyLoops);
// Temporary elimination makes it possible to simplify more operators, so do it later
Enqueue(SimplifyOperators);
Enqueue(ReplaceMethodCalls);
Enqueue(HandleBooleanAsInteger);
Enqueue(IntroduceCharCasts);
Enqueue(IntroduceEnumCasts);
Enqueue(ExpandCastExpressions);
// We need replace Int64 operations that was introduced by cast expressions
Enqueue(EmulateInt64);
// We need another operator simplification pass to simplify expressions created by cast expressions
Enqueue(SimplifyOperators);
Enqueue(DeoptimizeSwitchStatements);
Enqueue(CollapseNulls);
Enqueue(EliminateTemporaries);
Enqueue(SimplifyControlFlow);
Enqueue(EliminatePointlessFinallyBlocks);
Enqueue(OptimizeArrayEnumerators);
// We need another loop simplification pass because control flow has probably changed after the previous passes
Enqueue(SimplifyLoops);
if (Configuration.CodeGenerator.StripUnusedLoopNames.GetValueOrDefault(true))
Enqueue(EliminateUnusedLoopNames);
// We need to expand cast expressions again because previous passes may have made some more necessary
Enqueue(ExpandCastExpressions);
Enqueue(OptimizeAccessorMethods);
Enqueue(IntroducePackedArrays);
// If integer arithmetic hinting is enabled, we need to decompose mutation operators
// into normal binary operator expressions and/or comma expressions so that truncation can happen.
Enqueue(DecomposeMutationOperators);
Enqueue(FixupPointerArithmetic);
Enqueue(HoistAllocations);
Enqueue(EliminatePointlessRetargeting);
// HACK: Something about nullables is broken so we have to do this twice. WTF?
Enqueue(ReplaceMethodCalls);
}
// Pipeline stage implementations
private bool DecomposeMutationOperators () {
if (
Configuration.CodeGenerator.HintIntegerArithmetic.GetValueOrDefault(true) ||
Configuration.CodeGenerator.DecomposeAllMutationOperators.GetValueOrDefault(false)
) {
new DecomposeMutationOperators(
TypeSystem, TypeInfoProvider, FunctionSource,
Configuration.CodeGenerator.DecomposeAllMutationOperators.GetValueOrDefault(false)
).Visit(Function);
}
return true;
}
private bool FixupPointerArithmetic () {
if (Configuration.CodeGenerator.EnableUnsafeCode.GetValueOrDefault(false))
new UnsafeCodeTransforms(Configuration, TypeSystem, MethodTypes, FunctionSource).Visit(Function);
return true;
}
private bool IntroducePackedArrays () {
new IntroducePackedArrays(TypeSystem, MethodTypes).Visit(Function);
return true;
}
private bool SynthesizePropertySetterReturnValues () {
new SynthesizePropertySetterReturnValues(TypeSystem, TypeInfoProvider, FunctionSource).Visit(Function);
return true;
}
private bool OptimizeAccessorMethods () {
if (Configuration.CodeGenerator.PreferAccessorMethods.GetValueOrDefault(true)) {
new OptimizePropertyMutationAssignments(
TypeSystem, TypeInfoProvider, FunctionSource
).Visit(Function);
new ConvertPropertyAccessesToInvocations(
TypeSystem, TypeInfoProvider
).Visit(Function);
}
return true;
}
private bool EliminateUnusedLoopNames () {
var lnd = new LoopNameDetector();
lnd.Visit(Function);
lnd.EliminateUnusedLoopNames();
return true;
}
private bool OptimizeArrayEnumerators () {
return RunStaticAnalysisDependentTransform(
new OptimizeArrayEnumerators(Identifier, FunctionSource, TypeSystem)
);
}
private bool EliminatePointlessFinallyBlocks () {
return RunStaticAnalysisDependentTransform(
new EliminatePointlessFinallyBlocks(Identifier, FunctionSource, TypeSystem, TypeInfoProvider)
);
}
private bool SimplifyControlFlow () {
if (Configuration.CodeGenerator.EliminateRedundantControlFlow.GetValueOrDefault(true)) {
bool shouldInvalidate = false;
bool shouldCollapse = false;
bool shouldRun = true;
while (shouldRun) {
var cfs = new ControlFlowSimplifier();
cfs.Visit(Function);
shouldRun = cfs.MadeChanges;
shouldCollapse |= cfs.MadeChanges;
shouldInvalidate |= cfs.MadeChanges;
}
// HACK: Control flow simplification probably generated lots of nulls, so let's collapse them.
// This makes it possible for loop simplification to work right later on.
if (shouldCollapse)
CollapseNulls();
if (shouldInvalidate)
FunctionSource.InvalidateFirstPass(Identifier);
}
return true;
}
private bool FixupStructConstructorInvocations () {
new FixupStructConstructorInvocations(TypeSystem).Visit(Function);
return true;
}
private bool CollapseNulls () {
new CollapseNulls().Visit(Function);
return true;
}
private bool DeoptimizeSwitchStatements () {
new DeoptimizeSwitchStatements(TypeSystem).Visit(Function);
return true;
}
private bool ExpandCastExpressions () {
new ExpandCastExpressions(
TypeSystem, SpecialIdentifiers.JS, SpecialIdentifiers.JSIL, TypeInfoProvider, MethodTypes,
Configuration.CodeGenerator.EmulateInt64.GetValueOrDefault(true)
).Visit(Function);
return true;
}
private bool IntroduceEnumCasts () {
if (Configuration.CodeGenerator.IntroduceEnumCasts.GetValueOrDefault(true)) {
new IntroduceEnumCasts(
TypeSystem, SpecialIdentifiers.JS, TypeInfoProvider, MethodTypes, FunctionSource
).Visit(Function);
}
return true;
}
private bool IntroduceCharCasts () {
if (Configuration.CodeGenerator.IntroduceCharCasts.GetValueOrDefault(true)) {
new IntroduceCharCasts(
TypeSystem, SpecialIdentifiers.JS
).Visit(Function);
}
return true;
}
private bool HandleBooleanAsInteger () {
new HandleBooleanAsInteger(
TypeSystem, SpecialIdentifiers.JS
).Visit(Function);
return true;
}
private bool ReplaceMethodCalls () {
new ReplaceMethodCalls(
Function.Method.Reference,
SpecialIdentifiers.JSIL, SpecialIdentifiers.JS, TypeSystem
).Visit(Function);
return true;
}
private bool SimplifyOperators () {
if (Configuration.CodeGenerator.SimplifyOperators.GetValueOrDefault(true))
new SimplifyOperators(
SpecialIdentifiers.JSIL, SpecialIdentifiers.JS, TypeSystem
).Visit(Function);
return true;
}
private bool SimplifyLoops () {
if (Configuration.CodeGenerator.SimplifyLoops.GetValueOrDefault(true))
new SimplifyLoops(
TypeSystem, false
).Visit(Function);
return true;
}
private bool IntroduceVariableDeclarationsAndReferences () {
new IntroduceVariableDeclarations(
Function.AllVariables,
TypeInfoProvider
).Visit(Function);
new IntroduceVariableReferences(
SpecialIdentifiers.JSIL,
Function.AllVariables,
FunctionSource
).Visit(Function);
return true;
}
private bool EmulateStructAssignment () {
return RunStaticAnalysisDependentTransform(
new EmulateStructAssignment(
Identifier, FunctionSource,
TypeSystem,
TypeInfoProvider,
SpecialIdentifiers.CLR,
MethodTypes,
Configuration.CodeGenerator.EliminateStructCopies.GetValueOrDefault(true)
)
);
}
private bool EmulateInt64 () {
if (Translator.Configuration.CodeGenerator.EmulateInt64.GetValueOrDefault(true)) {
new EmulateInt64(
MethodTypes,
SpecialIdentifiers.TypeSystem
).Visit(Function);
}
return true;
}
private bool BuildLabelGroups () {
var la = new LabelAnalyzer();
la.BuildLabelGroups(Function);
Function.LabelGroupCount = la.LabelGroups.Count;
return true;
}
private bool EliminateTemporaries () {
if (Translator.Configuration.CodeGenerator.EliminateTemporaries.GetValueOrDefault(true)) {
var eliminated = new[] { false };
do {
if (!RunStaticAnalysisDependentTransform(new EliminateSingleUseTemporaries(
Identifier, FunctionSource, TypeSystem, Function.AllVariables, TypeInfoProvider
), (visitor) => {
eliminated[0] = visitor.EliminatedVariables.Count > 0;
}))
return false;
} while (eliminated[0]);
}
return true;
}
private bool HoistAllocations () {
if (Configuration.CodeGenerator.HoistAllocations.GetValueOrDefault(true)) {
new HoistAllocations(
Identifier, FunctionSource, TypeSystem, MethodTypes
).Visit(Function);
}
return true;
}
private bool EliminatePointlessRetargeting () {
if (Configuration.CodeGenerator.HoistAllocations.GetValueOrDefault(true))
return RunStaticAnalysisDependentTransform(new EliminatePointlessRetargeting(
Identifier, FunctionSource, TypeSystem, MethodTypes
));
else
return true;
}
}
public class FunctionTransformFailureException : Exception {
public FunctionTransformFailureException (string functionName, string pipelineStageName, Exception innerException)
: base (
String.Format(
"Function transform pipeline stage '{1}' failed on function '{0}':",
functionName, pipelineStageName
),
innerException
)
{
}
}
}