File: TestCompilerInlining.java

package info (click to toggle)
openjdk-11 11.0.22%2B7-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 781,236 kB
  • sloc: java: 5,174,754; xml: 1,192,262; cpp: 1,133,036; ansic: 461,316; javascript: 162,554; sh: 16,859; objc: 13,683; python: 4,753; asm: 3,570; makefile: 2,894; perl: 357; awk: 351; sed: 172; jsp: 24; csh: 3
file content (406 lines) | stat: -rw-r--r-- 14,661 bytes parent folder | download | duplicates (7)
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
/*
 * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

package jdk.jfr.event.compiler;

import jdk.internal.org.objectweb.asm.*;
import jdk.jfr.Recording;
import jdk.jfr.consumer.RecordedEvent;
import jdk.jfr.consumer.RecordedMethod;
import jdk.jfr.consumer.RecordedObject;
import jdk.test.lib.Asserts;
import jdk.test.lib.Platform;
import jdk.test.lib.jfr.EventNames;
import jdk.test.lib.jfr.Events;
import sun.hotspot.WhiteBox;

import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Executable;
import java.lang.reflect.Method;
import java.util.*;
import java.util.stream.IntStream;

/**
 * @test CompilerInliningTest
 * @bug 8073607
 * @key jfr
 * @summary Verifies that corresponding JFR events are emitted in case of inlining.
 * @requires vm.hasJFR
 *
 * @requires vm.opt.Inline == true | vm.opt.Inline == null
 * @library /test/lib
 * @modules java.base/jdk.internal.org.objectweb.asm
 *          jdk.jfr
 *
 * @build sun.hotspot.WhiteBox
 * @run main ClassFileInstaller sun.hotspot.WhiteBox
 *     sun.hotspot.WhiteBox$WhiteBoxPermission
 * @run main/othervm -Xbootclasspath/a:.
 *     -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI
 *     -Xbatch jdk.jfr.event.compiler.TestCompilerInlining
 */
public class TestCompilerInlining {
    private static final WhiteBox WHITE_BOX = WhiteBox.getWhiteBox();
    private static final int LEVEL_SIMPLE = 1;
    private static final int LEVEL_FULL_OPTIMIZATION = 4;
    private static final Executable ENTRY_POINT = getConstructor(TestCase.class);
    private static final String TEST_CASE_CLASS_NAME = TestCase.class.getName().replace('.', '/');

    public static void main(String[] args) throws Exception {
        InlineCalls inlineCalls = new InlineCalls(TestCase.class);
        inlineCalls.disableInline(getConstructor(Object.class));
        inlineCalls.disableInline(getMethod(TestCase.class, "qux", boolean.class));
        inlineCalls.forceInline(getMethod(TestCase.class, "foo"));
        inlineCalls.forceInline(getMethod(TestCase.class, "foo", int.class));
        inlineCalls.forceInline(getMethod(TestCase.class, "bar"));
        inlineCalls.forceInline(getMethod(TestCase.class, "baz"));

        Map<Call, Boolean> result = inlineCalls.getExpected(ENTRY_POINT);
        for (int level : determineAvailableLevels()) {
            testLevel(result, level);
        }
    }

    private static void testLevel(Map<Call, Boolean> expectedResult, int level) throws IOException {
        System.out.println("****** Testing level " + level + " *******");
        Recording r = new Recording();
        r.enable(EventNames.CompilerInlining);
        r.start();
        WHITE_BOX.enqueueMethodForCompilation(ENTRY_POINT, level);
        WHITE_BOX.deoptimizeMethod(ENTRY_POINT);
        r.stop();
        System.out.println("Expected:");

        List<RecordedEvent> events = Events.fromRecording(r);
        Set<Call> foundEvents = new HashSet<>();
        int foundRelevantEvent = 0;
        for (RecordedEvent event : events) {
            RecordedMethod callerObject = event.getValue("caller");
            RecordedObject calleeObject = event.getValue("callee");
            MethodDesc caller = methodToMethodDesc(callerObject);
            MethodDesc callee = ciMethodToMethodDesc(calleeObject);
            // only TestCase.* -> TestCase.* OR TestCase.* -> Object.<init> are tested/filtered
            if (caller.className.equals(TEST_CASE_CLASS_NAME) && (callee.className.equals(TEST_CASE_CLASS_NAME)
                    || (callee.className.equals("java/lang/Object") && callee.methodName.equals("<init>")))) {
                System.out.println(event);
                boolean succeeded = (boolean) event.getValue("succeeded");
                int bci = Events.assertField(event, "bci").atLeast(0).getValue();
                Call call = new Call(caller, callee, bci);
                foundRelevantEvent++;
                Boolean expected = expectedResult.get(call);
                Asserts.assertNotNull(expected, "Unexpected inlined call : " + call);
                Asserts.assertEquals(expected, succeeded, "Incorrect result for " + call);
                Asserts.assertTrue(foundEvents.add(call), "repeated event for " + call);
            }
        }
        Asserts.assertEquals(foundRelevantEvent, expectedResult.size(), String.format("not all events found at lavel %d. " + "found = '%s'. expected = '%s'", level, events, expectedResult.keySet()));
        System.out.println();
        System.out.println();
    }

    private static int[] determineAvailableLevels() {
        if (WHITE_BOX.getBooleanVMFlag("TieredCompilation")) {
            return IntStream.rangeClosed(LEVEL_SIMPLE, WHITE_BOX.getIntxVMFlag("TieredStopAtLevel").intValue()).toArray();
        }
        if (Platform.isServer() && !Platform.isEmulatedClient()) {
            return new int[] { LEVEL_FULL_OPTIMIZATION };
        }
        if (Platform.isClient() || Platform.isEmulatedClient()) {
            return new int[] { LEVEL_SIMPLE };
        }
        throw new Error("TESTBUG: unknown VM");
    }

    private static MethodDesc methodToMethodDesc(RecordedMethod method) {
        String internalClassName = method.getType().getName().replace('.', '/');
        String methodName = method.getValue("name");
        String methodDescriptor = method.getValue("descriptor");
        return new MethodDesc(internalClassName, methodName, methodDescriptor);
    }

    private static MethodDesc ciMethodToMethodDesc(RecordedObject ciMethod) {
        String internalClassName = ciMethod.getValue("type");
        String methodName = ciMethod.getValue("name");
        String methodDescriptor = ciMethod.getValue("descriptor");
        return new MethodDesc(internalClassName, methodName, methodDescriptor);
    }

    private static Method getMethod(Class<?> aClass, String name, Class<?>... params) {
        try {
            return aClass.getDeclaredMethod(name, params);
        } catch (NoSuchMethodException | SecurityException e) {
            throw new Error("TESTBUG : cannot get method " + name + Arrays.toString(params), e);
        }
    }

    private static Constructor<?> getConstructor(Class<?> aClass, Class<?>... params) {
        try {
            return aClass.getDeclaredConstructor(params);
        } catch (NoSuchMethodException | SecurityException e) {
            throw new Error("TESTBUG : cannot get constructor" + Arrays.toString(params), e);
        }
    }
}

class TestCase {
    public TestCase() {
        foo();
    }

    public void foo() {
        qux(true);
        bar();
        foo(2);
    }

    private void foo(int i) {
    }

    private void bar() {
        baz();
        qux(false);
        qux(true);
    }

    protected static double baz() {
        qux(false);
        return .0;
    }

    private static int qux(boolean b) {
        qux(b);
        return 0;
    }
}

/**
 * data structure for method call
 */
class Call {
    public final MethodDesc caller;
    public final MethodDesc callee;
    public final int bci;

    @Override
    public boolean equals(Object o) {
        if (this == o)
            return true;
        if (o == null || !(o instanceof Call))
            return false;

        Call call = (Call) o;

        if (bci != call.bci)
            return false;
        if (!callee.equals(call.callee))
            return false;
        if (!caller.equals(call.caller))
            return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = caller.hashCode();
        result = 31 * result + callee.hashCode();
        result = 47 * result + bci;
        return result;
    }

    public Call(MethodDesc caller, MethodDesc callee, int bci) {
        Objects.requireNonNull(caller);
        Objects.requireNonNull(callee);
        this.caller = caller;
        this.callee = callee;
        this.bci = bci;
    }

    @Override
    public String toString() {
        return String.format("Call{caller='%s', callee='%s', bci=%d}", caller, callee, bci);
    }
}

/**
 * data structure for method description
 */
class MethodDesc {
    public final String className;
    public final String methodName;
    public final String descriptor;

    public MethodDesc(Class<?> aClass, String methodName, String descriptor) {
        this(aClass.getName().replace('.', '/'), methodName, descriptor);
    }

    public MethodDesc(String className, String methodName, String descriptor) {
        Objects.requireNonNull(className);
        Objects.requireNonNull(methodName);
        Objects.requireNonNull(descriptor);
        this.className = className.replace('.', '/');
        this.methodName = methodName;
        this.descriptor = descriptor;
    }

    public MethodDesc(Executable executable) {
        Class<?> aClass = executable.getDeclaringClass();
        className = Type.getInternalName(aClass).replace('.', '/');

        if (executable instanceof Constructor<?>) {
            methodName = "<init>";
            descriptor = Type.getConstructorDescriptor((Constructor<?>) executable);
        } else {
            methodName = executable.getName();
            descriptor = Type.getMethodDescriptor((Method) executable);
        }

    }

    @Override
    public boolean equals(Object o) {
        if (this == o)
            return true;
        if (o == null || getClass() != o.getClass())
            return false;

        MethodDesc that = (MethodDesc) o;

        if (!className.equals(that.className))
            return false;
        if (!methodName.equals(that.methodName))
            return false;
        if (!descriptor.equals(that.descriptor))
            return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = className.hashCode();
        result = 31 * result + methodName.hashCode();
        result = 47 * result + descriptor.hashCode();
        return result;
    }

    @Override
    public String toString() {
        return String.format("MethodDesc{className='%s', methodName='%s', descriptor='%s'}", className, methodName, descriptor);
    }
}

/**
 * Aux class to get all calls in an arbitrary class.
 */
class InlineCalls {
    private static final WhiteBox WHITE_BOX = WhiteBox.getWhiteBox();

    private final Collection<Call> calls;
    private final Map<Call, Boolean> inline;

    public InlineCalls(Class<?> aClass) {
        calls = getCalls(aClass);
        inline = new HashMap<>();
    }

    /**
     * @return expected inline events
     */
    public Map<Call, Boolean> getExpected(Executable entry) {
        Map<Call, Boolean> result = new HashMap<>();
        Queue<MethodDesc> methods = new ArrayDeque<>();
        Set<MethodDesc> finished = new HashSet<>();
        methods.add(new MethodDesc(entry));
        while (!methods.isEmpty()) {
            MethodDesc method = methods.poll();
            if (finished.add(method)) {
                inline.entrySet().stream().filter(k -> k.getKey().caller.equals(method)).forEach(k -> {
                    result.put(k.getKey(), k.getValue());
                    if (k.getValue()) {
                        methods.add(k.getKey().callee);
                    }
                });
            }
        }

        return result;
    }

    public void disableInline(Executable executable) {
        WHITE_BOX.testSetDontInlineMethod(executable, true);
        MethodDesc md = new MethodDesc(executable);
        calls.stream().filter(c -> c.callee.equals(md)).forEach(c -> inline.put(c, false));
    }

    public void forceInline(Executable executable) {
        WHITE_BOX.testSetForceInlineMethod(executable, true);
        MethodDesc md = new MethodDesc(executable);
        calls.stream().filter(c -> c.callee.equals(md)).forEach(c -> inline.putIfAbsent(c, true));
    }

    private static Collection<Call> getCalls(Class<?> aClass) {
        List<Call> calls = new ArrayList<>();
        ClassWriter cw;
        ClassReader cr;
        try {
            cr = new ClassReader(aClass.getName());
        } catch (IOException e) {
            throw new Error("TESTBUG : unexpected IOE during class reading", e);
        }
        cw = new ClassWriter(cr, 0);
        ClassVisitor cv = new ClassVisitor(Opcodes.ASM5, cw) {
            @Override
            public MethodVisitor visitMethod(int access, String name, String desc, String descriptor, String[] exceptions) {
                System.out.println("Method: " +name);
                MethodVisitor mv = super.visitMethod(access, name, desc, descriptor, exceptions);
                return new CallTracer(aClass, name, desc, mv, calls);
            }
        };
        cr.accept(cv, 0);

        return calls;
    }

    private static class CallTracer extends MethodVisitor {
        private final MethodDesc caller;
        private Collection<Call> calls;

        public CallTracer(Class<?> aClass, String name, String desc, MethodVisitor mv, Collection<Call> calls) {
            super(Opcodes.ASM5, mv);
            caller = new MethodDesc(aClass.getName(), name, desc);
            this.calls = calls;
        }

        @Override
        public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) {
            Label label = new Label();
            visitLabel(label);
            super.visitMethodInsn(opcode, owner, name, desc, itf);
            calls.add(new Call(caller, new MethodDesc(owner, name, desc), label.getOffset()));
        }
    }
}