-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathControlFlowSimplifier.cs
More file actions
490 lines (378 loc) · 17.5 KB
/
Copy pathControlFlowSimplifier.cs
File metadata and controls
490 lines (378 loc) · 17.5 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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using ICSharpCode.Decompiler.ILAst;
using JSIL.Ast;
using JSIL.Internal;
using Mono.Cecil;
namespace JSIL.Transforms {
public class ControlFlowSimplifier : JSAstVisitor {
private class LabelGroupLabelData {
public readonly List<string> ExitTargetLabels = new List<string>();
public string DirectExitLabel;
public string RecursiveExitLabel;
public int TimesUsedAsRecursiveExitTarget;
public int UntargettedExitCount;
}
private class LabelGroupData : Dictionary<string, LabelGroupLabelData> {
}
private static int TraceLevel = 0;
private int TotalUntargettedExits = 0;
private readonly Stack<JSBlockStatement> BlockStack = new Stack<JSBlockStatement>();
private readonly List<int> AbsoluteJumpsSeenStack = new List<int>();
private readonly Stack<JSSwitchCase> SwitchCaseStack = new Stack<JSSwitchCase>();
private readonly Stack<LabelGroupData> LabelGroupStack = new Stack<LabelGroupData>();
private readonly Stack<int> LoopIndexStack = new Stack<int>();
private JSStatement PreviousLabelledStatement = null;
private JSStatement CurrentLabelledStatement = null;
private JSSwitchCase LastSwitchCase = null;
public bool MadeChanges = false;
public ControlFlowSimplifier () {
AbsoluteJumpsSeenStack.Add(0);
}
public void VisitNode (JSSwitchStatement ss) {
CheckForFallthrough(ss);
AbsoluteJumpsSeenStack.Add(0);
VisitChildren(ss);
AbsoluteJumpsSeenStack.RemoveAt(AbsoluteJumpsSeenStack.Count - 1);
}
public void VisitNode (JSSwitchCase sc) {
SwitchCaseStack.Push(sc);
AbsoluteJumpsSeenStack.Add(0);
if (TraceLevel >= 3) {
if (sc.Values != null)
Console.WriteLine("// Entering case {0}", sc.Values.FirstOrDefault());
else
Console.WriteLine("// Entering case default");
}
VisitChildren(sc);
if (TraceLevel >= 3)
Console.WriteLine("// Exiting case");
AbsoluteJumpsSeenStack.RemoveAt(AbsoluteJumpsSeenStack.Count - 1);
SwitchCaseStack.Pop();
}
public void VisitNode (JSBlockStatement bs) {
CheckForFallthrough(bs);
var lastSwitchCase = LastSwitchCase;
var thisSwitchCase = ParentSwitchCase;
LastSwitchCase = thisSwitchCase;
var parentLabelGroup = ParentNode as JSLabelGroupStatement;
var isControlFlow = bs.IsControlFlow ||
(thisSwitchCase != lastSwitchCase) ||
(parentLabelGroup != null);
if (TraceLevel >= 3)
Console.WriteLine("// Entering block {0}", bs.Label ?? bs.GetType().Name);
if (isControlFlow) {
if (TraceLevel >= 3)
Console.WriteLine("// Count reset");
AbsoluteJumpsSeenStack.Add(0);
}
BlockStack.Push(bs);
VisitChildren(bs);
BlockStack.Pop();
if (TraceLevel >= 3)
Console.WriteLine("// Exiting block");
if (isControlFlow)
AbsoluteJumpsSeenStack.RemoveAt(AbsoluteJumpsSeenStack.Count - 1);
}
private JSSwitchCase ParentSwitchCase {
get {
return SwitchCaseStack.LastOrDefault();
}
}
private int AbsoluteJumpsSeen {
get {
if (AbsoluteJumpsSeenStack.Count <= 0)
return 0;
return AbsoluteJumpsSeenStack[AbsoluteJumpsSeenStack.Count - 1];
}
set {
if (AbsoluteJumpsSeenStack.Count <= 0)
throw new InvalidOperationException("Stack empty");
AbsoluteJumpsSeenStack[AbsoluteJumpsSeenStack.Count - 1] = value;
}
}
protected void VisitControlFlowNode (JSNode node) {
var stackSlice = Stack.Take(3).ToArray();
var parentEs = stackSlice[1] as JSExpressionStatement;
var parentBlock = stackSlice[2] as JSBlockStatement;
if ((parentEs != null) && (parentBlock == BlockStack.Peek())) {
AbsoluteJumpsSeen += 1;
if (AbsoluteJumpsSeen > 1) {
if (TraceLevel >= 1)
Console.WriteLine("// Eliminating {0}", node);
var replacement = new JSNullExpression();
ParentNode.ReplaceChild(node, replacement);
MadeChanges = true;
return;
} else {
if (TraceLevel >= 4)
Console.WriteLine("// Not eliminating {0}", node);
}
}
VisitChildren(node);
}
private void CheckForFallthrough (JSStatement statement) {
if (String.IsNullOrWhiteSpace(statement.Label))
return;
bool failed = true;
PreviousLabelledStatement = CurrentLabelledStatement;
CurrentLabelledStatement = statement;
if (PreviousLabelledStatement == null)
return;
if (PreviousLabelledStatement.Label == null) {
PreviousLabelledStatement = null;
return;
}
var lastChildStatement = PreviousLabelledStatement.AllChildrenRecursive
.OfType<JSStatement>()
.LastOrDefault((s) => !s.IsNull);
var lastEs = lastChildStatement as JSExpressionStatement;
if ((lastEs != null) &&
(
(lastEs.Expression is JSGotoExpression) ||
(lastEs.Expression is JSBreakExpression) ||
(lastEs.Expression is JSContinueExpression)
)
) {
if (TraceLevel >= 3)
Console.WriteLine("// Not recording fallthrough from {0} to {1} because {0} ends with control flow ({2})", PreviousLabelledStatement.Label, CurrentLabelledStatement.Label, lastEs.Expression);
return;
}
if (LabelGroupStack.Count > 0) {
foreach (var lg in LabelGroupStack) {
LabelGroupLabelData labelData;
if (lg.TryGetValue(PreviousLabelledStatement.Label, out labelData)) {
failed = false;
if (TraceLevel >= 2)
Console.WriteLine("// Recording fallthrough from {0} to {1}", PreviousLabelledStatement.Label, CurrentLabelledStatement.Label);
labelData.ExitTargetLabels.Add(CurrentLabelledStatement.Label);
}
}
}
if ((TraceLevel >= 2) && failed)
Console.WriteLine("// Failed to record fallthrough from {0} to {1}", PreviousLabelledStatement.Label, CurrentLabelledStatement.Label);
}
private void RecordUntargettedExit () {
TotalUntargettedExits += 1;
if (LabelGroupStack.Count > 0) {
var enclosingLabelledStatement = Stack.OfType<JSStatement>().LastOrDefault((n) => n.Label != null);
if (enclosingLabelledStatement != null) {
foreach (var lg in LabelGroupStack) {
LabelGroupLabelData labelData;
if (lg.TryGetValue(enclosingLabelledStatement.Label, out labelData))
labelData.UntargettedExitCount += 1;
}
}
}
}
public void VisitNode (JSReturnExpression re) {
RecordUntargettedExit();
VisitChildren(re);
}
public void VisitNode (JSContinueExpression ce) {
if (ce.TargetLoop.HasValue && LoopIndexStack.Contains(ce.TargetLoop.Value))
RecordUntargettedExit();
VisitControlFlowNode(ce);
}
public void VisitNode (JSBreakExpression be) {
if (be.TargetLoop.HasValue && LoopIndexStack.Contains(be.TargetLoop.Value))
RecordUntargettedExit();
VisitControlFlowNode(be);
}
public void VisitNode (JSGotoExpression ge) {
if (LabelGroupStack.Count > 0) {
var enclosingLabelledStatement = Stack.OfType<JSStatement>().LastOrDefault((n) => n.Label != null);
if (enclosingLabelledStatement != null) {
foreach (var lg in LabelGroupStack) {
LabelGroupLabelData labelData;
if (lg.TryGetValue(enclosingLabelledStatement.Label, out labelData)) {
if (ge is JSExitLabelGroupExpression) {
labelData.UntargettedExitCount += 1;
} else {
labelData.ExitTargetLabels.Add(ge.TargetLabel);
}
}
}
}
}
VisitControlFlowNode(ge);
}
private string ComputeRecursiveExitLabel (LabelGroupData data, string label) {
var labelData = data[label];
var recursiveExit = labelData.DirectExitLabel;
if (recursiveExit == null)
return null;
while (recursiveExit != null) {
LabelGroupLabelData targetLabelData;
if (!data.TryGetValue(recursiveExit, out targetLabelData)) {
// The label is part of another label group.
return null;
}
if (targetLabelData.DirectExitLabel == null) {
if (
(targetLabelData.ExitTargetLabels.Count == 0) /* &&
FIXME: Is this right?
(targetLabelData.UntargettedExitCount <= 1) */
)
return recursiveExit;
else
return null;
} else {
// Cycle detected
if (recursiveExit == targetLabelData.DirectExitLabel)
return null;
recursiveExit = targetLabelData.DirectExitLabel;
}
// Cycle detected
if (recursiveExit == label)
return null;
}
return null;
}
private void ExtractExitLabel (JSLabelGroupStatement lgs) {
var exitLabel = lgs.ExitLabel;
var originalLabelName = exitLabel.Label;
if (exitLabel.AllChildrenRecursive.OfType<JSGotoExpression>().Any()) {
if (TraceLevel >= 1)
Console.WriteLine("// Cannot extract exit label '{0}' from label group because it contains a goto or exit", originalLabelName);
return;
}
// The label before this label may have fallen through, so we need to append an ExitLabelGroup
var previousLabel = lgs.BeforeExitLabel;
if (previousLabel != null) {
var exitStatement = new JSExpressionStatement(new JSExitLabelGroupExpression(lgs));
var previousBlock = previousLabel as JSBlockStatement;
if (previousBlock != null) {
previousBlock.Statements.Add(exitStatement);
} else {
var replacement = new JSBlockStatement(
previousLabel, exitStatement
);
replacement.Label = previousLabel.Label;
replacement.IsControlFlow = true;
previousLabel.Label = null;
lgs.ReplaceChild(previousLabel, replacement);
}
}
lgs.Labels.Remove(originalLabelName);
exitLabel.Label = null;
exitLabel.IsControlFlow = false;
{
var replacement = new JSBlockStatement(
lgs,
exitLabel
);
exitLabel.OriginalLabel = originalLabelName;
// Extract the exit label so it directly follows the label group
ParentNode.ReplaceChild(lgs, replacement);
// Find and convert all the gotos so that they instead break out of the label group
var gotos = DeoptimizeSwitchStatements.FindGotos(lgs, originalLabelName);
foreach (var g in gotos)
lgs.ReplaceChildRecursive(g, new JSExitLabelGroupExpression(lgs));
}
if (TraceLevel >= 1)
Console.WriteLine("// Extracted exit label '{0}' from label group", originalLabelName);
MadeChanges = true;
}
public void VisitNode (JSLabelGroupStatement lgs) {
CheckForFallthrough(lgs);
var data = new LabelGroupData();
LabelGroupStack.Push(data);
foreach (var key in lgs.Labels.Keys)
data.Add(key.Value, new LabelGroupLabelData());
VisitChildren(lgs);
// Scan all the labels to determine their direct exit label, if any
foreach (var kvp in data) {
var targetLabels = kvp.Value.ExitTargetLabels.Distinct().ToArray();
if (
(targetLabels.Length == 1) &&
(kvp.Value.UntargettedExitCount == 0)
) {
kvp.Value.DirectExitLabel = targetLabels[0];
} else {
kvp.Value.DirectExitLabel = null;
}
}
// Scan all the labels again to determine their recursive exit label
foreach (var kvp in data) {
var rel = kvp.Value.RecursiveExitLabel = ComputeRecursiveExitLabel(data, kvp.Key);
if (rel != null)
data[rel].TimesUsedAsRecursiveExitTarget += 1;
}
// If we have one label that is the recursive exit target for all other labels, we can turn it into the exit label
var recursiveExitTargets = data.Where(
(kvp) => kvp.Value.TimesUsedAsRecursiveExitTarget > 0
).ToArray();
if (recursiveExitTargets.Length == 1) {
var onlyRecursiveExitTarget = recursiveExitTargets[0].Key;
var exitLabel = lgs.ExitLabel;
var newExitLabel = lgs.Labels[onlyRecursiveExitTarget];
var newExitLabelData = data[newExitLabel.Label];
if (
(newExitLabelData.ExitTargetLabels.Count == 0) &&
(newExitLabelData.UntargettedExitCount == 0) &&
(newExitLabel != lgs.Labels.LastOrDefault().Value)
) {
if (TraceLevel >= 1)
Console.WriteLine("// Cannot mark label '{0}' as exit label because it falls through and is not the last label", onlyRecursiveExitTarget);
} else if (exitLabel != null) {
if (exitLabel != newExitLabel) {
if (TraceLevel >= 1)
Console.WriteLine("// Cannot mark label '{0}' as exit label because this labelgroup already has one", onlyRecursiveExitTarget);
}
} else {
if (TraceLevel >= 1)
Console.WriteLine("// Marking label '{0}' as exit label", onlyRecursiveExitTarget);
lgs.ExitLabel = newExitLabel;
MadeChanges = true;
}
}
if ((lgs.ExitLabel != null) && (lgs.Labels.Count > 1))
ExtractExitLabel(lgs);
LabelGroupStack.Pop();
}
public void VisitNode (JSLoopStatement ls) {
CheckForFallthrough(ls);
LoopIndexStack.Push(ls.Index.GetValueOrDefault(-1));
VisitChildren(ls);
LoopIndexStack.Pop();
}
public void VisitNode (JSWhileLoop wl) {
// Extract the last non-block statement from the body of the while loop
var lastChild = wl.Children.LastOrDefault();
while (lastChild is JSBlockStatement) {
var bs = lastChild as JSBlockStatement;
if (bs.IsControlFlow)
break;
else
lastChild = bs.Statements.LastOrDefault();
}
// Is it a continue expression?
var lastES = lastChild as JSExpressionStatement;
if (lastES != null) {
var lastContinue = lastES.Expression as JSContinueExpression;
if (
(lastContinue != null) &&
(lastContinue.TargetLoop == wl.Index)
) {
// Spurious continue, so murder it
wl.ReplaceChildRecursive(lastContinue, new JSNullExpression());
if (TraceLevel >= 1)
Console.WriteLine("// Pruning spurious continue expression {0}", lastContinue);
MadeChanges = true;
}
}
LoopIndexStack.Push(wl.Index.GetValueOrDefault(-1));
VisitChildren(wl);
LoopIndexStack.Pop();
}
public void VisitNode (JSStatement jss) {
CheckForFallthrough(jss);
VisitChildren(jss);
}
}
}