-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOptimizer.java
216 lines (185 loc) · 8.92 KB
/
Optimizer.java
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
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.classfile.ClassFile;
import java.lang.classfile.ClassFile.ClassHierarchyResolverOption;
import java.lang.classfile.ClassHierarchyResolver;
import java.lang.classfile.CodeBuilder;
import java.lang.classfile.CodeElement;
import java.lang.classfile.Instruction;
import java.lang.classfile.attribute.CodeAttribute;
import java.lang.classfile.instruction.ConstantInstruction;
import java.lang.classfile.instruction.InvokeInstruction;
import java.lang.constant.ClassDesc;
import java.lang.constant.MethodTypeDesc;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;
import static java.lang.classfile.ClassFile.ConstantPoolSharingOption.NEW_POOL;
import static java.lang.classfile.ClassFile.DebugElementsOption.DROP_DEBUG;
import static java.lang.classfile.ClassFile.LineNumbersOption.DROP_LINE_NUMBERS;
import static java.lang.classfile.ClassTransform.transformingMethods;
import static java.lang.classfile.Opcode.IADD;
import static java.lang.classfile.Opcode.ISUB;
import static java.nio.charset.StandardCharsets.UTF_8;
/**
* Optimize the bytecode in a given jar by applying peephole optimizations.
*/
@SuppressWarnings("preview")
public class Optimizer {
public static void main(String[] args) {
if (args.length < 2 || args.length > 3) {
System.err.println("Usage: java --enable-preview Optimizer.java <input-jar> <output-jar> [number of passes: default 1]");
System.exit(1);
}
var input = new File(args[0]);
if (!input.exists()) {
System.err.println("Input file " + args[0] + " does not exist");
System.exit(2);
}
var output = new File(args[1]);
if (output.exists()) {
output.delete();
}
var numberOfPasses = 1;
if (args.length == 3) {
try {
numberOfPasses = Integer.parseInt(args[2]);
} catch (NumberFormatException e) {
System.err.println("Invalid number of passes: " + args[2]);
System.exit(3);
}
}
optimizeJar(input, output, numberOfPasses);
}
private static void optimizeJar(File input, File output, int numberOfPasses) {
try (
var jarFile = new JarFile(input);
var outputStream = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(output)))
) {
var resolver = ClassHierarchyResolver.defaultResolver()
.orElse(new JarClassHierarchyResolver(jarFile))
.cached();
var entries = jarFile.entries();
while (entries.hasMoreElements()) {
var entry = entries.nextElement();
try (var inputStream = jarFile.getInputStream(entry)) {
var newEntry = new JarEntry(entry);
outputStream.putNextEntry(newEntry);
if (entry.getName().endsWith(".class")) {
var originalBytes = inputStream.readAllBytes();
try {
var optimizedBytes = originalBytes;
for (int pass = 0; pass < numberOfPasses; pass++) {
optimizedBytes = optimizeClass(resolver, optimizedBytes);
}
outputStream.write(optimizedBytes);
} catch (Exception e) {
// If there's an error during optimization,
// copy over the original bytes instead.
System.err.println("Error optimizing " + entry.getName() + ": " + e.getMessage());
outputStream.write(originalBytes);
}
} else {
// Copy other files across unchanged.
inputStream.transferTo(outputStream);
}
outputStream.closeEntry();
}
}
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
private static byte[] optimizeClass(ClassHierarchyResolver resolver, byte[] bytes) {
// Parse the class bytes into a class model.
// Drop line numbers and debug info, to simplify the peephole pattern matching.
var classModel = ClassFile.of(DROP_LINE_NUMBERS, DROP_DEBUG).parse(bytes);
// When transforming the class, use a new constant pool instead of adding new
// entries to the existing one.
return ClassFile.of(NEW_POOL, ClassHierarchyResolverOption.of(resolver))
.transformClass(classModel, transformingMethods(
(methodBuilder, methodElement) -> {
if (methodElement instanceof CodeAttribute codeAttribute) {
methodBuilder.withCode(codeBuilder -> {
optimizeCodeAttribute(codeAttribute, codeBuilder);
});
} else {
methodBuilder.with(methodElement);
}
}
));
}
private static void optimizeCodeAttribute(CodeAttribute codeAttribute, CodeBuilder codeBuilder) {
var windowSize = 5;
var elements = codeAttribute.elementList();
var currentIndex = 0;
while (currentIndex < elements.size()) {
// Create a fixed size window with up to windowSize elements and the remainder nulls.
var window = new CodeElement[windowSize];
for (int i = 0; i < windowSize && currentIndex + i < elements.size(); i++) {
window[i] = elements.get(currentIndex + i);
}
// Optimize X +- 0 -> X
if (window[0] instanceof ConstantInstruction c && c.constantValue().equals(0) &&
window[1] instanceof Instruction i && (i.opcode() == IADD || i.opcode() == ISUB)) {
// Skip the two matched elements and emit no new elements.
currentIndex += 2;
continue;
}
// Optimize append("foo").append("bar") -> append("foobar")
if (window[0] instanceof ConstantInstruction c1 && c1.constantValue() instanceof String s1 &&
window[1] instanceof InvokeInstruction i1 &&
i1.owner().asSymbol().equals(ClassDesc.of("java.lang.StringBuilder")) &&
i1.method().name().equalsString("append") &&
i1.typeSymbol().equals(MethodTypeDesc.of(ClassDesc.of("java.lang.StringBuilder"), ClassDesc.of("java.lang.String"))) &&
window[2] instanceof ConstantInstruction c2 && c2.constantValue() instanceof String s2 &&
window[3] instanceof InvokeInstruction i2 &&
i2.owner().equals(i1.owner()) && i1.method().equals(i2.method()) && i1.type().equals(i2.type())
) {
var concat = s1 + s2;
// Emit the concatenated string constant, if it fits.
if (concat.getBytes(UTF_8).length <= 65535) {
codeBuilder
.ldc(concat)
.invokevirtual(i1.owner().asSymbol(), i1.method().name().stringValue(), i1.typeSymbol());
// Skip the four matched instructions.
currentIndex += 4;
continue;
}
}
// No optimizations, so continue to the next element.
codeBuilder.accept(elements.get(currentIndex++));
}
}
/**
* Provides a {@link ClassHierarchyResolver} to resolve classes from a given
* {@link JarFile}.
*/
private static class JarClassHierarchyResolver implements ClassHierarchyResolver {
private final ClassHierarchyResolver resourceClassHierarchyResolver;
public JarClassHierarchyResolver(JarFile jarFile) {
this.resourceClassHierarchyResolver = ClassHierarchyResolver.ofResourceParsing(
classDesc -> {
var desc = classDesc.descriptorString();
// Remove the L and ; from the descriptor e.g. Ljava/lang/Object -> java/lang/Object
var internalName = desc.substring(1, desc.length() - 1);
var jarEntry = jarFile.getJarEntry(internalName + ".class");
// Class not found
if (jarEntry == null) return null;
try {
return jarFile.getInputStream(jarEntry);
} catch (IOException e) {
// Error reading class
return null;
}
}
);
}
@Override
public ClassHierarchyInfo getClassInfo(ClassDesc classDesc) {
return resourceClassHierarchyResolver.getClassInfo(classDesc);
}
}
}