0
# Compilation and Optimization
1
2
Compilation infrastructure providing optimized call targets, compiler directives, assumption-based optimizations, and performance profiling.
3
4
## Capabilities
5
6
### OptimizedCallTarget
7
8
Represents a compiled and optimized executable unit that can be invoked with high performance.
9
10
```java { .api }
11
/**
12
* Optimized implementation of CallTarget that provides compilation
13
* and performance monitoring capabilities
14
*/
15
public abstract class OptimizedCallTarget implements CallTarget, ReplaceObserver {
16
/** Executes the call target with given arguments */
17
public final Object call(Object... arguments);
18
19
/** Checks if this call target's compiled code is still valid */
20
public abstract boolean isValid();
21
22
/** Invalidates the compiled code, forcing recompilation */
23
public abstract void invalidate();
24
25
/** Invalidates with a specific reason for debugging */
26
public abstract void invalidate(String reason);
27
28
/** Returns the number of times this call target has been invoked */
29
public abstract int getCallCount();
30
31
/** Returns the time spent compiling this call target (in nanoseconds) */
32
public abstract long getCompilationTime();
33
34
/** Checks if this call target is currently being compiled */
35
public abstract boolean isCompiling();
36
37
/** Checks if this call target has been compiled */
38
public abstract boolean isCompiled();
39
40
/** Forces compilation of this call target */
41
public abstract void compile();
42
43
/** Returns compilation metadata and statistics */
44
public abstract CompilationResult getCompilationResult();
45
46
/** Returns the root node associated with this call target */
47
public final RootNode getRootNode();
48
49
/** Sets a custom name for this call target */
50
public final void setName(String name);
51
52
/** Returns the name of this call target */
53
public final String getName();
54
}
55
```
56
57
**Usage Examples:**
58
59
```java
60
import com.oracle.truffle.api.Truffle;
61
import com.oracle.truffle.api.nodes.RootNode;
62
import com.oracle.truffle.runtime.OptimizedCallTarget;
63
64
// Create an optimized call target
65
RootNode rootNode = new MyLanguageRootNode();
66
OptimizedCallTarget callTarget = (OptimizedCallTarget) Truffle.getRuntime()
67
.createCallTarget(rootNode);
68
69
// Monitor compilation status
70
if (!callTarget.isCompiled()) {
71
System.out.println("Call count: " + callTarget.getCallCount());
72
73
// Force compilation if needed
74
callTarget.compile();
75
}
76
77
// Check if optimizations are still valid
78
if (!callTarget.isValid()) {
79
System.out.println("Call target was invalidated, will recompile");
80
}
81
```
82
83
### CompilerDirectives
84
85
Static utility methods that provide hints and directives to the optimizing compiler.
86
87
```java { .api }
88
/**
89
* Compiler optimization directives and hints for the Graal compiler
90
*/
91
public final class CompilerDirectives {
92
/** Forces transfer from compiled code to interpreter */
93
public static void transferToInterpreter();
94
95
/** Forces transfer to interpreter and invalidates compiled code */
96
public static void transferToInterpreterAndInvalidate();
97
98
/** Checks if currently executing in interpreter mode */
99
public static boolean inInterpreter();
100
101
/** Checks if currently executing in compiled code */
102
public static boolean inCompiledCode();
103
104
/** Hints that a value should be treated as compilation constant */
105
public static boolean isCompilationConstant(Object value);
106
107
/** Hints that a condition is likely to be true */
108
public static boolean injectBranchProbability(double probability, boolean condition);
109
110
/** Marks a code path as unlikely to be executed */
111
public static void bailout(String reason);
112
113
/** Ensures a value is not optimized away */
114
public static <T> T blackhole(T value);
115
116
/** Hints that a method call should be inlined */
117
public static void ensureVirtualized(Object object);
118
119
/** Hints that an exception path is slow */
120
public static RuntimeException shouldNotReachHere();
121
122
/** Hints that an exception path is slow with message */
123
public static RuntimeException shouldNotReachHere(String message);
124
125
/** Hints that an exception path is slow with cause */
126
public static RuntimeException shouldNotReachHere(Throwable cause);
127
}
128
```
129
130
**Usage Examples:**
131
132
```java
133
public class MyLanguageNode extends Node {
134
135
@CompilerDirectives.CompilationFinal
136
private int constantValue = 42;
137
138
public Object execute(VirtualFrame frame) {
139
if (CompilerDirectives.inInterpreter()) {
140
// This code only runs in interpreter
141
collectProfile();
142
}
143
144
// Provide branch probability hint
145
if (CompilerDirectives.injectBranchProbability(0.9, isCommonCase())) {
146
return fastPath();
147
} else {
148
// Unlikely path - may cause deoptimization
149
CompilerDirectives.transferToInterpreterAndInvalidate();
150
return slowPath();
151
}
152
}
153
}
154
```
155
156
### OptimizedAssumption
157
158
Represents an assumption that enables aggressive optimizations but can be invalidated when conditions change.
159
160
```java { .api }
161
/**
162
* Optimized implementation of Assumption that enables aggressive
163
* compiler optimizations based on runtime assumptions
164
*/
165
public final class OptimizedAssumption implements Assumption {
166
/** Checks if this assumption is still valid */
167
public boolean isValid();
168
169
/** Invalidates this assumption and all dependent compiled code */
170
public void invalidate();
171
172
/** Invalidates this assumption with a specific message */
173
public void invalidate(String message);
174
175
/** Returns the name of this assumption */
176
public String getName();
177
178
/** Checks the assumption and throws exception if invalid */
179
public void check() throws InvalidAssumptionException;
180
181
/** Checks if the assumption has been checked in compiled code */
182
public boolean isValidAssumption();
183
}
184
```
185
186
**Usage Examples:**
187
188
```java
189
import com.oracle.truffle.api.Assumption;
190
import com.oracle.truffle.api.Truffle;
191
192
public class ClassLayout {
193
private final Assumption stableLayout;
194
195
public ClassLayout() {
196
this.stableLayout = Truffle.getRuntime()
197
.createAssumption("Stable class layout");
198
}
199
200
public Object getProperty(String name) {
201
try {
202
// Check assumption before using cached layout
203
stableLayout.check();
204
return getCachedProperty(name);
205
} catch (InvalidAssumptionException e) {
206
// Layout changed, update cache
207
updateLayout();
208
return getProperty(name);
209
}
210
}
211
212
public void addProperty(String name) {
213
// Adding property invalidates layout assumption
214
stableLayout.invalidate("Property added: " + name);
215
updateLayout();
216
}
217
}
218
```
219
220
### Compilation Events and Results
221
222
Information about compilation process and results.
223
224
```java { .api }
225
/**
226
* Result of a compilation attempt
227
*/
228
public interface CompilationResult {
229
/** Returns the target that was compiled */
230
OptimizedCallTarget getTarget();
231
232
/** Checks if compilation was successful */
233
boolean isSuccess();
234
235
/** Returns the compilation failure reason if any */
236
String getFailureReason();
237
238
/** Returns compilation time in nanoseconds */
239
long getTimeCompilationFinished();
240
241
/** Returns the number of nodes in compiled code */
242
int getNodeCount();
243
244
/** Returns the size of generated code in bytes */
245
int getCodeSize();
246
}
247
248
/**
249
* Actions to take when compilation fails
250
*/
251
public enum CompilationFailureAction {
252
/** Silently continue with interpreter */
253
Silent,
254
255
/** Print compilation failure to console */
256
Print,
257
258
/** Throw exception on compilation failure */
259
Throw,
260
261
/** Exit the VM on compilation failure */
262
ExitVM,
263
264
/** Perform detailed diagnostics */
265
Diagnose
266
}
267
```
268
269
### Loop Optimization
270
271
Specialized nodes for optimized loop execution and On-Stack Replacement (OSR).
272
273
```java { .api }
274
/**
275
* Optimized loop node that supports OSR compilation
276
*/
277
public abstract class OptimizedLoopNode extends Node implements LoopNode {
278
/** Executes the loop with given frame */
279
public abstract void execute(VirtualFrame frame);
280
281
/** Returns the repeating node inside this loop */
282
public abstract RepeatingNode getRepeatingNode();
283
284
/** Checks if OSR is enabled for this loop */
285
public abstract boolean isOSREnabled();
286
287
/** Returns OSR compilation metadata */
288
public abstract OSRMetadata getOSRMetadata();
289
}
290
291
/**
292
* OSR (On-Stack Replacement) optimized loop node
293
*/
294
public final class OptimizedOSRLoopNode extends OptimizedLoopNode {
295
/** Creates a new OSR loop node */
296
public static OptimizedOSRLoopNode create(RepeatingNode repeatingNode);
297
298
/** Executes the loop with OSR support */
299
public void execute(VirtualFrame frame);
300
301
/** Forces OSR compilation */
302
public void forceOSR();
303
304
/** Returns the OSR call target */
305
public CallTarget getOSRCallTarget();
306
}
307
```
308
309
**Usage Examples:**
310
311
```java
312
// Creating an optimized loop
313
RepeatingNode repeatingNode = new MyRepeatingNode();
314
OptimizedLoopNode loopNode = OptimizedOSRLoopNode.create(repeatingNode);
315
316
// The runtime automatically handles OSR compilation
317
// when the loop runs for a long time
318
```
319
320
## Common Types
321
322
```java { .api }
323
public interface Assumption {
324
/** Checks if the assumption is still valid */
325
boolean isValid();
326
327
/** Invalidates the assumption */
328
void invalidate();
329
330
/** Invalidates the assumption with a message */
331
void invalidate(String message);
332
333
/** Returns the assumption name */
334
String getName();
335
336
/** Checks the assumption, throwing exception if invalid */
337
void check() throws InvalidAssumptionException;
338
}
339
340
public final class InvalidAssumptionException extends SlowPathException {
341
/** Creates exception for invalid assumption */
342
public InvalidAssumptionException(Assumption assumption);
343
344
/** Returns the invalidated assumption */
345
public Assumption getAssumption();
346
}
347
348
public interface RepeatingNode extends Node.Child {
349
/** Executes one iteration of the repeating node */
350
boolean executeRepeating(VirtualFrame frame);
351
}
352
353
public interface LoopNode extends Node.Child {
354
/** Executes the entire loop */
355
void execute(VirtualFrame frame);
356
357
/** Returns the repeating node */
358
RepeatingNode getRepeatingNode();
359
}
360
```