1 /*
   2  * Copyright (c) 2012, 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 package org.graalvm.compiler.hotspot;
  24 
  25 import static java.lang.Thread.currentThread;
  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.Arrays;
  39 import java.util.Date;
  40 import java.util.Deque;
  41 import java.util.Locale;
  42 import java.util.concurrent.ConcurrentLinkedDeque;
  43 
  44 import org.graalvm.compiler.debug.CSVUtil;
  45 import org.graalvm.compiler.debug.Management;
  46 import org.graalvm.compiler.options.Option;
  47 import org.graalvm.compiler.options.OptionValue;
  48 import com.sun.management.ThreadMXBean;
  49 
  50 import jdk.vm.ci.hotspot.HotSpotInstalledCode;
  51 import jdk.vm.ci.hotspot.HotSpotResolvedJavaMethod;
  52 
  53 @SuppressWarnings("unused")
  54 public final class CompilationStatistics {
  55 
  56     public static class Options {
  57         // @formatter:off
  58         @Option(help = "Enables CompilationStatistics.")
  59         public static final OptionValue<Boolean> UseCompilationStatistics = new OptionValue<>(false);
  60         // @formatter:on
  61     }
  62 
  63     private static final long RESOLUTION = 100000000;
  64     private static final boolean ENABLED = Options.UseCompilationStatistics.getValue();
  65 
  66     private static final CompilationStatistics DUMMY = new CompilationStatistics(null, false);
  67 
  68     private static ConcurrentLinkedDeque<CompilationStatistics> list = new ConcurrentLinkedDeque<>();
  69 
  70     private static final ThreadLocal<Deque<CompilationStatistics>> current = new ThreadLocal<Deque<CompilationStatistics>>() {
  71 
  72         @Override
  73         protected Deque<CompilationStatistics> initialValue() {
  74             return new ArrayDeque<>();
  75         }
  76     };
  77 
  78     @Retention(RetentionPolicy.RUNTIME)
  79     @Target(ElementType.FIELD)
  80     private static @interface NotReported {
  81     }
  82 
  83     @Retention(RetentionPolicy.RUNTIME)
  84     @Target(ElementType.FIELD)
  85     private static @interface TimeValue {
  86     }
  87 
  88     private static long zeroTime = System.nanoTime();
  89 
  90     private static long getThreadAllocatedBytes() {
  91         ThreadMXBean thread = (ThreadMXBean) Management.getThreadMXBean();
  92         return thread.getThreadAllocatedBytes(currentThread().getId());
  93     }
  94 
  95     @NotReported private final long startTime;
  96     @NotReported private long threadAllocatedBytesStart;
  97 
  98     private int bytecodeCount;
  99     private int codeSize;
 100     @TimeValue private long duration;
 101     private long memoryUsed;
 102     private final boolean osr;
 103     private final String holder;
 104     private final String name;
 105     private final String signature;
 106 
 107     private CompilationStatistics(HotSpotResolvedJavaMethod method, boolean osr) {
 108         this.osr = osr;
 109         if (method != null) {
 110             holder = method.getDeclaringClass().getName();
 111             name = method.getName();
 112             signature = method.getSignature().toMethodDescriptor();
 113             startTime = System.nanoTime();
 114             bytecodeCount = method.getCodeSize();
 115             threadAllocatedBytesStart = getThreadAllocatedBytes();
 116         } else {
 117             holder = "";
 118             name = "";
 119             signature = "";
 120             startTime = 0;
 121         }
 122     }
 123 
 124     public void finish(HotSpotResolvedJavaMethod method, HotSpotInstalledCode code) {
 125         if (ENABLED) {
 126             duration = System.nanoTime() - startTime;
 127             codeSize = (int) code.getCodeSize();
 128             memoryUsed = getThreadAllocatedBytes() - threadAllocatedBytesStart;
 129             if (current.get().getLast() != this) {
 130                 throw new RuntimeException("mismatch in finish()");
 131             }
 132             current.get().removeLast();
 133         }
 134     }
 135 
 136     public static CompilationStatistics current() {
 137         return current.get().isEmpty() ? null : current.get().getLast();
 138     }
 139 
 140     public static CompilationStatistics create(HotSpotResolvedJavaMethod method, boolean isOSR) {
 141         if (ENABLED) {
 142             CompilationStatistics stats = new CompilationStatistics(method, isOSR);
 143             list.add(stats);
 144             current.get().addLast(stats);
 145             return stats;
 146         } else {
 147             return DUMMY;
 148         }
 149     }
 150 
 151     @SuppressWarnings("deprecation")
 152     public static void clear(String dumpName) {
 153         if (!ENABLED) {
 154             return;
 155         }
 156         try {
 157             ConcurrentLinkedDeque<CompilationStatistics> snapshot = list;
 158             long snapshotZeroTime = zeroTime;
 159 
 160             list = new ConcurrentLinkedDeque<>();
 161             zeroTime = System.nanoTime();
 162 
 163             Date now = new Date();
 164             String dateString = (now.getYear() + 1900) + "-" + (now.getMonth() + 1) + "-" + now.getDate() + "-" + now.getHours() + "" + now.getMinutes();
 165 
 166             dumpCompilations(snapshot, dumpName, dateString);
 167 
 168             try (FileOutputStream fos = new FileOutputStream("timeline_" + dateString + "_" + dumpName + ".csv", true); PrintStream out = new PrintStream(fos)) {
 169 
 170                 long[] timeSpent = new long[10000];
 171                 int maxTick = 0;
 172                 for (CompilationStatistics stats : snapshot) {
 173                     long start = stats.startTime - snapshotZeroTime;
 174                     long duration = stats.duration;
 175                     if (start < 0) {
 176                         duration -= -start;
 177                         start = 0;
 178                     }
 179 
 180                     int tick = (int) (start / RESOLUTION);
 181                     long timeLeft = RESOLUTION - (start % RESOLUTION);
 182 
 183                     while (tick < timeSpent.length && duration > 0) {
 184                         if (tick > maxTick) {
 185                             maxTick = tick;
 186                         }
 187                         timeSpent[tick] += Math.min(timeLeft, duration);
 188                         duration -= timeLeft;
 189                         tick++;
 190                         timeLeft = RESOLUTION;
 191                     }
 192                 }
 193                 String timelineName = System.getProperty("stats.timeline.name");
 194                 if (timelineName != null && !timelineName.isEmpty()) {
 195                     out.printf("%s%c", CSVUtil.Escape.escape(timelineName), CSVUtil.SEPARATOR);
 196                 }
 197                 for (int i = 0; i < maxTick; i++) {
 198                     out.printf("%d%c", normalize(timeSpent[i]), CSVUtil.SEPARATOR);
 199                 }
 200                 // print last column
 201                 out.printf("%d", normalize(timeSpent[maxTick]));
 202                 out.println();
 203             }
 204         } catch (Exception e) {
 205             throw new RuntimeException(e);
 206         }
 207     }
 208 
 209     private static long normalize(long time) {
 210         return time * 100 / RESOLUTION;
 211     }
 212 
 213     protected static void dumpCompilations(ConcurrentLinkedDeque<CompilationStatistics> snapshot, String dumpName, String dateString) throws IllegalAccessException, FileNotFoundException {
 214         String fileName = "compilations_" + dateString + "_" + dumpName + ".csv";
 215         char separator = '\t';
 216         try (PrintStream out = new PrintStream(fileName)) {
 217             // output the list of all compilations
 218 
 219             Field[] declaredFields = CompilationStatistics.class.getDeclaredFields();
 220             ArrayList<Field> fields = new ArrayList<>();
 221             for (Field field : declaredFields) {
 222                 if (!Modifier.isStatic(field.getModifiers()) && !field.isAnnotationPresent(NotReported.class)) {
 223                     fields.add(field);
 224                 }
 225             }
 226             String format = CSVUtil.buildFormatString("%s", separator, fields.size());
 227             CSVUtil.Escape.println(out, separator, CSVUtil.QUOTE, CSVUtil.ESCAPE, format, fields.toArray());
 228             for (CompilationStatistics stats : snapshot) {
 229                 Object[] values = new Object[fields.size()];
 230                 for (int i = 0; i < fields.size(); i++) {
 231                     Field field = fields.get(i);
 232                     if (field.isAnnotationPresent(TimeValue.class)) {
 233                         double value = field.getLong(stats) / 1000000d;
 234                         values[i] = String.format(Locale.ENGLISH, "%.3f", value);
 235                     } else {
 236                         values[i] = field.get(stats);
 237                     }
 238                 }
 239                 CSVUtil.Escape.println(out, separator, CSVUtil.QUOTE, CSVUtil.ESCAPE, format, values);
 240             }
 241         }
 242     }
 243 }