-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAllocationHoisting.cs
More file actions
298 lines (249 loc) · 11.2 KB
/
Copy pathAllocationHoisting.cs
File metadata and controls
298 lines (249 loc) · 11.2 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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using JSIL.Ast;
using JSIL.Internal;
using Mono.Cecil;
namespace JSIL.Transforms {
public class HoistAllocations : StaticAnalysisJSAstVisitor {
private struct VariableCacheKey {
public readonly JSExpression Array;
public readonly JSExpression Index;
public VariableCacheKey (JSExpression array, JSExpression index) {
Array = array;
Index = index;
}
public override int GetHashCode () {
return Array.GetHashCode() ^ Index.GetHashCode();
}
public override bool Equals (object obj) {
if (obj is VariableCacheKey)
return Equals((VariableCacheKey)obj);
else
return false;
}
public bool Equals (VariableCacheKey obj) {
return Object.Equals(Array, obj.Array) &&
Object.Equals(Index, obj.Index);
}
}
private struct Identifier {
public readonly string Text;
public readonly JSRawOutputIdentifier Object;
public Identifier (string text, JSRawOutputIdentifier @object) {
Text = text;
Object = @object;
}
}
private struct PendingDeclaration {
public readonly string Name;
public readonly TypeReference Type;
public readonly JSExpression Expression;
public readonly JSExpression DefaultValue;
public PendingDeclaration (string name, TypeReference type, JSExpression expression, JSExpression defaultValue) {
Name = name;
Type = type;
Expression = expression;
DefaultValue = defaultValue;
}
}
public readonly TypeSystem TypeSystem;
public readonly MethodTypeFactory MethodTypes;
private readonly List<PendingDeclaration> ToDeclare =
new List<PendingDeclaration>();
private readonly Dictionary<VariableCacheKey, JSVariable> CachedHoistedVariables =
new Dictionary<VariableCacheKey, JSVariable>();
private FunctionAnalysis1stPass FirstPass = null;
private int HoistedVariableCount = 0;
private JSFunctionExpression Function;
public HoistAllocations (
QualifiedMemberIdentifier member,
IFunctionSource functionSource,
TypeSystem typeSystem,
MethodTypeFactory methodTypes
)
: base (member, functionSource) {
TypeSystem = typeSystem;
MethodTypes = methodTypes;
}
public void VisitNode (JSFunctionExpression fn) {
Function = fn;
FirstPass = GetFirstPass(Function.Method.QualifiedIdentifier);
VisitChildren(fn);
if (ToDeclare.Count > 0) {
int i = 0;
var vds = new JSVariableDeclarationStatement();
foreach (var pd in ToDeclare) {
vds.Declarations.Add(
new JSBinaryOperatorExpression(
JSOperator.Assignment, pd.Expression,
pd.DefaultValue ?? new JSDefaultValueLiteral(pd.Type),
pd.Type
)
);
}
fn.Body.Statements.Insert(i++, vds);
InvalidateFirstPass();
}
}
private JSVariable MakeTemporaryVariable (TypeReference type, out string id, JSExpression defaultValue = null) {
string _id = id = string.Format("$hoisted{0:X2}", HoistedVariableCount++);
MethodReference methodRef = null;
if (Function.Method != null)
methodRef = Function.Method.Reference;
// So introspection knows about it
var result = new JSVariable(id, type, methodRef);
Function.AllVariables.Add(_id, result);
ToDeclare.Add(new PendingDeclaration(id, type, result, defaultValue));
return result;
}
bool DoesValueEscapeFromInvocation (JSInvocationExpression invocation, JSExpression argumentExpression, bool includeReturn) {
if (
(invocation != null) &&
(invocation.JSMethod != null) &&
(invocation.JSMethod.Reference != null)
) {
var methodDef = invocation.JSMethod.Reference.Resolve();
var secondPass = FunctionSource.GetSecondPass(invocation.JSMethod, Function.Method.QualifiedIdentifier);
if ((secondPass != null) && (methodDef != null)) {
// HACK
var argumentIndex = invocation.Arguments.Select(
(a, i) => new { argument = a, index = i })
.FirstOrDefault((_) => _.argument.SelfAndChildrenRecursive.Contains(argumentExpression));
if (argumentIndex != null) {
var argumentName = methodDef.Parameters[argumentIndex.index].Name;
return secondPass.DoesVariableEscape(argumentName, includeReturn);
}
} else if (secondPass != null) {
// HACK for methods that do not have resolvable references. In this case, if NONE of their arguments escape, we're probably still okay.
if (secondPass.GetNumberOfEscapingVariables(includeReturn) == 0)
return false;
}
}
return true;
}
public void VisitNode (JSNewArrayElementReference naer) {
var isInsideLoop = (Stack.Any((node) => node is JSLoopStatement));
var parentPassByRef = ParentNode as JSPassByReferenceExpression;
var parentInvocation = Stack.OfType<JSInvocationExpression>().FirstOrDefault();
var doesValueEscape = DoesValueEscapeFromInvocation(parentInvocation, naer, true);
if (
isInsideLoop &&
(parentPassByRef != null) &&
(parentInvocation != null) &&
!doesValueEscape
) {
var replacement = CreateHoistedVariable(
(hoistedVariable) => JSInvocationExpression.InvokeMethod(
new JSFakeMethod("retarget", hoistedVariable.GetActualType(TypeSystem), new TypeReference[] { TypeSystem.Object, TypeSystem.Int32 }, MethodTypes),
hoistedVariable, new JSExpression[] { naer.Array, naer.Index }
),
naer.GetActualType(TypeSystem),
naer.MakeUntargeted()
);
ParentNode.ReplaceChild(naer, replacement);
VisitReplacement(replacement);
}
VisitChildren(naer);
}
public void VisitNode (JSNewPackedArrayElementProxy npaep) {
var isInsideLoop = (Stack.Any((node) => node is JSLoopStatement));
var parentInvocation = Stack.OfType<JSInvocationExpression>().FirstOrDefault();
var doesValueEscape = (parentInvocation != null) &&
DoesValueEscapeFromInvocation(parentInvocation, npaep, true);
if (
isInsideLoop &&
(
(parentInvocation == null) ||
!doesValueEscape
)
) {
var replacement = CreateHoistedVariable(
(hoistedVariable) =>
new JSRetargetPackedArrayElementProxy(
hoistedVariable, npaep.Array, npaep.Index
),
npaep.GetActualType(TypeSystem),
npaep.Array,
npaep.Index,
npaep.MakeUntargeted()
);
ParentNode.ReplaceChild(npaep, replacement);
VisitReplacement(replacement);
}
VisitChildren(npaep);
}
public void VisitNode (JSNewExpression newexp) {
var type = newexp.GetActualType(TypeSystem);
var isStruct = TypeUtil.IsStruct(type);
var isInsideLoop = (Stack.Any((node) => node is JSLoopStatement));
var parentInvocation = ParentNode as JSInvocationExpression;
var doesValueEscape = DoesValueEscapeFromInvocation(parentInvocation, newexp, false);
if (isStruct &&
isInsideLoop &&
(parentInvocation != null) &&
!doesValueEscape
) {
var replacement = CreateHoistedVariable(
(hoistedVariable) => new JSCommaExpression(
JSInvocationExpression.InvokeMethod(
type, new JSMethod(newexp.ConstructorReference, newexp.Constructor, MethodTypes, null), hoistedVariable,
newexp.Arguments.ToArray(), false
),
hoistedVariable
),
type
);
ParentNode.ReplaceChild(newexp, replacement);
VisitReplacement(replacement);
} else {
VisitChildren(newexp);
}
}
private JSExpression CreateHoistedVariable (
Func<JSVariable, JSExpression> update,
TypeReference type,
JSExpression defaultValue = null
) {
if (update == null)
throw new ArgumentNullException("update");
string id;
var hoistedVariable = MakeTemporaryVariable(type, out id, defaultValue);
var replacement = update(hoistedVariable);
return replacement;
}
private JSExpression CreateHoistedVariable (
Func<JSVariable, JSExpression> update,
TypeReference type,
JSExpression array,
JSExpression index,
JSExpression defaultValue = null
) {
Func<JSNode, bool> filter = (e) =>
(e is JSUnaryOperatorExpression) ||
(e is JSInvocationExpression);
if (update == null)
throw new ArgumentNullException("update");
// If the array or index expressions are not simple, don't attempt to cache.
if (
(array == null) ||
(index == null) ||
index.AllChildrenRecursive.Any(filter) ||
array.AllChildrenRecursive.Any(filter)
)
return CreateHoistedVariable(
update, type, defaultValue
);
var key = new VariableCacheKey(array, index);
JSVariable hoistedVariable;
if (!CachedHoistedVariables.TryGetValue(key, out hoistedVariable)) {
string id;
hoistedVariable = MakeTemporaryVariable(type, out id, defaultValue);
CachedHoistedVariables[key] = hoistedVariable;
}
var replacement = update(hoistedVariable);
return replacement;
}
}
}