1 /*
2  * Copyright (c) 2012, 2018, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.
8  *
9  * This code is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12  * version 2 for more details (a copy is included in the LICENSE file that
13  * accompanied this code).
14  *
15  * You should have received a copy of the GNU General Public License version
16  * 2 along with this work; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18  *
19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20  * or visit www.oracle.com if you need additional information or have any
21  * questions.
22  */
23 
24 
25 package org.graalvm.compiler.hotspot;
26 
27 import java.io.FileNotFoundException;
28 import java.io.FileOutputStream;
29 import java.io.PrintStream;
30 import java.lang.annotation.ElementType;
31 import java.lang.annotation.Retention;
32 import java.lang.annotation.RetentionPolicy;
33 import java.lang.annotation.Target;
34 import java.lang.reflect.Field;
35 import java.lang.reflect.Modifier;
36 import java.util.ArrayDeque;
37 import java.util.ArrayList;
38 import java.util.Date;
39 import java.util.Deque;
40 import java.util.Locale;
41 import java.util.concurrent.ConcurrentLinkedDeque;
42 
43 import org.graalvm.compiler.debug.CSVUtil;
44 import org.graalvm.compiler.options.Option;
45 import org.graalvm.compiler.options.OptionKey;
46 import org.graalvm.compiler.options.OptionValues;
47 import org.graalvm.compiler.serviceprovider.GraalServices;
48 
49 import jdk.vm.ci.hotspot.HotSpotInstalledCode;
50 import jdk.vm.ci.hotspot.HotSpotResolvedJavaMethod;
51 
52 @SuppressWarnings("unused")
53 public final class CompilationStatistics {
54 
55     public static class Options {
56         // @formatter:off
57         @Option(help = "Enables CompilationStatistics.")
58         public static final OptionKey<Boolean> UseCompilationStatistics = new OptionKey<>(false);
59         // @formatter:on
60     }
61 
62     private static final long RESOLUTION = 100000000;
63 
64     private static final CompilationStatistics DUMMY = new CompilationStatistics(null, false);
65 
66     private static ConcurrentLinkedDeque<CompilationStatistics> list = new ConcurrentLinkedDeque<>();
67 
68     private static final ThreadLocal<Deque<CompilationStatistics>> current = new ThreadLocal<Deque<CompilationStatistics>>() {
69 
70         @Override
71         protected Deque<CompilationStatistics> initialValue() {
72             return new ArrayDeque<>();
73         }
74     };
75 
76     @Retention(RetentionPolicy.RUNTIME)
77     @Target(ElementType.FIELD)
78     private static @interface NotReported {
79     }
80 
81     @Retention(RetentionPolicy.RUNTIME)
82     @Target(ElementType.FIELD)
83     private static @interface TimeValue {
84     }
85 
86     private static long zeroTime = System.nanoTime();
87 
getThreadAllocatedBytes()88     private static long getThreadAllocatedBytes() {
89         return GraalServices.getCurrentThreadAllocatedBytes();
90     }
91 
92     @NotReported private final long startTime;
93     @NotReported private long threadAllocatedBytesStart;
94 
95     private int bytecodeCount;
96     private int codeSize;
97     @TimeValue private long duration;
98     private long memoryUsed;
99     private final boolean osr;
100     private final String holder;
101     private final String name;
102     private final String signature;
103 
CompilationStatistics(HotSpotResolvedJavaMethod method, boolean osr)104     private CompilationStatistics(HotSpotResolvedJavaMethod method, boolean osr) {
105         this.osr = osr;
106         if (method != null) {
107             holder = method.getDeclaringClass().getName();
108             name = method.getName();
109             signature = method.getSignature().toMethodDescriptor();
110             startTime = System.nanoTime();
111             bytecodeCount = method.getCodeSize();
112             threadAllocatedBytesStart = getThreadAllocatedBytes();
113         } else {
114             assert DUMMY == null : "only DUMMY has no method";
115             holder = "";
116             name = "";
117             signature = "";
118             startTime = 0;
119         }
120     }
121 
finish(HotSpotResolvedJavaMethod method, HotSpotInstalledCode code)122     public void finish(HotSpotResolvedJavaMethod method, HotSpotInstalledCode code) {
123         if (isEnabled()) {
124             duration = System.nanoTime() - startTime;
125             codeSize = (int) code.getCodeSize();
126             memoryUsed = getThreadAllocatedBytes() - threadAllocatedBytesStart;
127             if (current.get().getLast() != this) {
128                 throw new RuntimeException("mismatch in finish()");
129             }
130             current.get().removeLast();
131         }
132     }
133 
current()134     public static CompilationStatistics current() {
135         return current.get().isEmpty() ? null : current.get().getLast();
136     }
137 
create(OptionValues options, HotSpotResolvedJavaMethod method, boolean isOSR)138     public static CompilationStatistics create(OptionValues options, HotSpotResolvedJavaMethod method, boolean isOSR) {
139         if (Options.UseCompilationStatistics.getValue(options)) {
140             CompilationStatistics stats = new CompilationStatistics(method, isOSR);
141             list.add(stats);
142             current.get().addLast(stats);
143             return stats;
144         } else {
145             return DUMMY;
146         }
147     }
148 
isEnabled()149     public boolean isEnabled() {
150         return this != DUMMY;
151     }
152 
153     @SuppressWarnings("deprecation")
clear(String dumpName)154     public static void clear(String dumpName) {
155         try {
156             ConcurrentLinkedDeque<CompilationStatistics> snapshot = list;
157             long snapshotZeroTime = zeroTime;
158 
159             list = new ConcurrentLinkedDeque<>();
160             zeroTime = System.nanoTime();
161 
162             Date now = new Date();
163             String dateString = (now.getYear() + 1900) + "-" + (now.getMonth() + 1) + "-" + now.getDate() + "-" + now.getHours() + "" + now.getMinutes();
164 
165             dumpCompilations(snapshot, dumpName, dateString);
166 
167             try (FileOutputStream fos = new FileOutputStream("timeline_" + dateString + "_" + dumpName + ".csv", true); PrintStream out = new PrintStream(fos)) {
168 
169                 long[] timeSpent = new long[10000];
170                 int maxTick = 0;
171                 for (CompilationStatistics stats : snapshot) {
172                     long start = stats.startTime - snapshotZeroTime;
173                     long duration = stats.duration;
174                     if (start < 0) {
175                         duration -= -start;
176                         start = 0;
177                     }
178 
179                     int tick = (int) (start / RESOLUTION);
180                     long timeLeft = RESOLUTION - (start % RESOLUTION);
181 
182                     while (tick < timeSpent.length && duration > 0) {
183                         if (tick > maxTick) {
184                             maxTick = tick;
185                         }
186                         timeSpent[tick] += Math.min(timeLeft, duration);
187                         duration -= timeLeft;
188                         tick++;
189                         timeLeft = RESOLUTION;
190                     }
191                 }
192                 String timelineName = System.getProperty("stats.timeline.name");
193                 if (timelineName != null && !timelineName.isEmpty()) {
194                     out.printf("%s%c", CSVUtil.Escape.escape(timelineName), CSVUtil.SEPARATOR);
195                 }
196                 for (int i = 0; i < maxTick; i++) {
197                     out.printf("%d%c", normalize(timeSpent[i]), CSVUtil.SEPARATOR);
198                 }
199                 // print last column
200                 out.printf("%d", normalize(timeSpent[maxTick]));
201                 out.println();
202             }
203         } catch (Exception e) {
204             throw new RuntimeException(e);
205         }
206     }
207 
normalize(long time)208     private static long normalize(long time) {
209         return time * 100 / RESOLUTION;
210     }
211 
dumpCompilations(ConcurrentLinkedDeque<CompilationStatistics> snapshot, String dumpName, String dateString)212     protected static void dumpCompilations(ConcurrentLinkedDeque<CompilationStatistics> snapshot, String dumpName, String dateString) throws IllegalAccessException, FileNotFoundException {
213         String fileName = "compilations_" + dateString + "_" + dumpName + ".csv";
214         char separator = '\t';
215         try (PrintStream out = new PrintStream(fileName)) {
216             // output the list of all compilations
217 
218             Field[] declaredFields = CompilationStatistics.class.getDeclaredFields();
219             ArrayList<Field> fields = new ArrayList<>();
220             for (Field field : declaredFields) {
221                 if (!Modifier.isStatic(field.getModifiers()) && !field.isAnnotationPresent(NotReported.class)) {
222                     fields.add(field);
223                 }
224             }
225             String format = CSVUtil.buildFormatString("%s", separator, fields.size());
226             CSVUtil.Escape.println(out, separator, CSVUtil.QUOTE, CSVUtil.ESCAPE, format, fields.toArray());
227             for (CompilationStatistics stats : snapshot) {
228                 Object[] values = new Object[fields.size()];
229                 for (int i = 0; i < fields.size(); i++) {
230                     Field field = fields.get(i);
231                     if (field.isAnnotationPresent(TimeValue.class)) {
232                         double value = field.getLong(stats) / 1000000d;
233                         values[i] = String.format(Locale.ENGLISH, "%.3f", value);
234                     } else {
235                         values[i] = field.get(stats);
236                     }
237                 }
238                 CSVUtil.Escape.println(out, separator, CSVUtil.QUOTE, CSVUtil.ESCAPE, format, values);
239             }
240         }
241     }
242 }
243