1 /*
   2  * Copyright (c) 2011, 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.printer;
  26 
  27 import static org.graalvm.compiler.debug.DebugConfig.asJavaMethod;
  28 
  29 import java.io.IOException;
  30 import java.nio.channels.ClosedByInterruptException;
  31 import java.util.ArrayList;
  32 import java.util.Arrays;
  33 import java.util.Collections;
  34 import java.util.Date;
  35 import java.util.HashMap;
  36 import java.util.List;
  37 import java.util.Map;
  38 import java.util.WeakHashMap;
  39 
  40 import org.graalvm.compiler.debug.DebugContext;
  41 import org.graalvm.compiler.debug.DebugDumpHandler;
  42 import org.graalvm.compiler.debug.DebugDumpScope;
  43 import org.graalvm.compiler.debug.DebugOptions;
  44 import org.graalvm.compiler.debug.GraalError;
  45 import org.graalvm.compiler.debug.TTY;
  46 import org.graalvm.compiler.graph.Graph;
  47 import org.graalvm.compiler.nodes.StructuredGraph;
  48 import org.graalvm.compiler.options.OptionValues;
  49 import org.graalvm.compiler.phases.contract.NodeCostUtil;
  50 import org.graalvm.compiler.serviceprovider.GraalServices;
  51 
  52 import jdk.vm.ci.meta.JavaMethod;
  53 import jdk.vm.ci.meta.ResolvedJavaMethod;
  54 
  55 //JaCoCo Exclude
  56 
  57 /**
  58  * Observes compilation events and uses {@link BinaryGraphPrinter} to generate a graph
  59  * representation that can be inspected with the Graph Visualizer.
  60  */
  61 public class GraphPrinterDumpHandler implements DebugDumpHandler {
  62 
  63     private static final int FAILURE_LIMIT = 8;
  64     private final GraphPrinterSupplier printerSupplier;
  65     protected GraphPrinter printer;
  66     private List<String> previousInlineContext;
  67     private int[] dumpIds = {};
  68     private int failuresCount;
  69     private Map<Graph, List<String>> inlineContextMap;
  70     private final String jvmArguments;
  71     private final String sunJavaCommand;
  72 
  73     @FunctionalInterface
  74     public interface GraphPrinterSupplier {
  75         GraphPrinter get(DebugContext ctx, Graph graph) throws IOException;
  76     }
  77 
  78     /**
  79      * Creates a new {@link GraphPrinterDumpHandler}.
  80      *
  81      * @param printerSupplier Supplier used to create the GraphPrinter. Should supply an optional or
  82      *            null in case of failure.
  83      */
  84     public GraphPrinterDumpHandler(GraphPrinterSupplier printerSupplier) {
  85         this.printerSupplier = printerSupplier;
  86         /* Add the JVM and Java arguments to the graph properties to help identify it. */
  87         this.jvmArguments = jvmArguments();
  88         this.sunJavaCommand = System.getProperty("sun.java.command");
  89     }
  90 
  91     private static String jvmArguments() {
  92         List<String> inputArguments = GraalServices.getInputArguments();
  93         if (inputArguments != null) {
  94             return String.join(" ", inputArguments);
  95         }
  96         return "unknown";
  97     }
  98 
  99     private void ensureInitialized(DebugContext ctx, Graph graph) {
 100         if (printer == null) {
 101             if (failuresCount >= FAILURE_LIMIT) {
 102                 return;
 103             }
 104             previousInlineContext = new ArrayList<>();
 105             inlineContextMap = new WeakHashMap<>();
 106             DebugContext debug = graph.getDebug();
 107             try {
 108                 printer = printerSupplier.get(ctx, graph);
 109             } catch (IOException e) {
 110                 handleException(debug, e);
 111             }
 112         }
 113     }
 114 
 115     private int nextDumpId() {
 116         int depth = previousInlineContext.size();
 117         if (dumpIds.length < depth) {
 118             dumpIds = Arrays.copyOf(dumpIds, depth);
 119         }
 120         return dumpIds[depth - 1]++;
 121     }
 122 
 123     @Override
 124     @SuppressWarnings("try")
 125     public void dump(DebugContext debug, Object object, final String format, Object... arguments) {
 126         OptionValues options = debug.getOptions();
 127         if (object instanceof Graph && DebugOptions.PrintGraph.getValue(options)) {
 128             final Graph graph = (Graph) object;
 129             ensureInitialized(debug, graph);
 130             if (printer == null) {
 131                 return;
 132             }
 133 
 134             // Get all current JavaMethod instances in the context.
 135             List<String> inlineContext = getInlineContext(graph);
 136 
 137             if (inlineContext != previousInlineContext) {
 138                 Map<Object, Object> properties = new HashMap<>();
 139                 properties.put("graph", graph.toString());
 140                 addCompilationId(properties, graph);
 141                 if (inlineContext.equals(previousInlineContext)) {
 142                     /*
 143                      * two different graphs have the same inline context, so make sure they appear
 144                      * in different folders by closing and reopening the top scope.
 145                      */
 146                     int inlineDepth = previousInlineContext.size() - 1;
 147                     closeScope(debug, inlineDepth);
 148                     openScope(debug, inlineContext.get(inlineDepth), inlineDepth, properties);
 149                 } else {
 150                     // Check for method scopes that must be closed since the previous dump.
 151                     for (int i = 0; i < previousInlineContext.size(); ++i) {
 152                         if (i >= inlineContext.size() || !inlineContext.get(i).equals(previousInlineContext.get(i))) {
 153                             for (int inlineDepth = previousInlineContext.size() - 1; inlineDepth >= i; --inlineDepth) {
 154                                 closeScope(debug, inlineDepth);
 155                             }
 156                             break;
 157                         }
 158                     }
 159                     // Check for method scopes that must be opened since the previous dump.
 160                     for (int i = 0; i < inlineContext.size(); ++i) {
 161                         if (i >= previousInlineContext.size() || !inlineContext.get(i).equals(previousInlineContext.get(i))) {
 162                             for (int inlineDepth = i; inlineDepth < inlineContext.size(); ++inlineDepth) {
 163                                 openScope(debug, inlineContext.get(inlineDepth), inlineDepth, inlineDepth == inlineContext.size() - 1 ? properties : null);
 164                             }
 165                             break;
 166                         }
 167                     }
 168                 }
 169             }
 170 
 171             // Save inline context for next dump.
 172             previousInlineContext = inlineContext;
 173 
 174             // Capture before creating the sandbox
 175             String currentScopeName = debug.getCurrentScopeName();
 176             try (DebugContext.Scope s = debug.sandbox("PrintingGraph", null)) {
 177                 // Finally, output the graph.
 178                 Map<Object, Object> properties = new HashMap<>();
 179                 properties.put("graph", graph.toString());
 180                 properties.put("scope", currentScopeName);
 181                 if (graph instanceof StructuredGraph) {
 182                     properties.put("compilationIdentifier", ((StructuredGraph) graph).compilationId());
 183                     try {
 184                         int size = NodeCostUtil.computeGraphSize((StructuredGraph) graph);
 185                         properties.put("node-cost graph size", size);
 186                     } catch (Throwable t) {
 187                         properties.put("node-cost-exception", t.getMessage());
 188                     }
 189                 }
 190                 printer.print(debug, graph, properties, nextDumpId(), format, arguments);
 191             } catch (IOException e) {
 192                 handleException(debug, e);
 193             } catch (Throwable e) {
 194                 throw debug.handle(e);
 195             }
 196         }
 197     }
 198 
 199     void handleException(DebugContext debug, IOException e) {
 200         if (debug != null && DebugOptions.DumpingErrorsAreFatal.getValue(debug.getOptions())) {
 201             throw new GraalError(e);
 202         }
 203         if (e instanceof ClosedByInterruptException) {
 204             /*
 205              * The current dumping was aborted by an interrupt so treat this as a transient failure.
 206              */
 207             failuresCount = 0;
 208         } else {
 209             failuresCount++;
 210         }
 211         printer = null;
 212         e.printStackTrace(TTY.out);
 213         if (failuresCount > FAILURE_LIMIT) {
 214             TTY.println("Too many failures with dumping. Disabling dump in thread " + Thread.currentThread());
 215         }
 216     }
 217 
 218     private static void addCompilationId(Map<Object, Object> properties, final Graph graph) {
 219         if (graph instanceof StructuredGraph) {
 220             properties.put("compilationId", ((StructuredGraph) graph).compilationId());
 221         }
 222     }
 223 
 224     private List<String> getInlineContext(Graph graph) {
 225         List<String> result = inlineContextMap.get(graph);
 226         if (result == null) {
 227             result = new ArrayList<>();
 228             Object lastMethodOrGraph = null;
 229             boolean graphSeen = false;
 230             DebugContext debug = graph.getDebug();
 231             for (Object o : debug.context()) {
 232                 if (o == graph) {
 233                     graphSeen = true;
 234                 }
 235 
 236                 if (o instanceof DebugDumpScope) {
 237                     DebugDumpScope debugDumpScope = (DebugDumpScope) o;
 238                     if (debugDumpScope.decorator && !result.isEmpty()) {
 239                         result.set(result.size() - 1, debugDumpScope.name + ":" + result.get(result.size() - 1));
 240                     } else {
 241                         result.add(debugDumpScope.name);
 242                     }
 243                 } else {
 244                     addMethodContext(result, o, lastMethodOrGraph);
 245                 }
 246                 if (o instanceof JavaMethod || o instanceof Graph) {
 247                     lastMethodOrGraph = o;
 248                 }
 249             }
 250             if (result.size() == 2 && result.get(1).startsWith("TruffleGraal")) {
 251                 result.clear();
 252                 result.add("Graal Graphs");
 253             }
 254             if (result.isEmpty()) {
 255                 result.add(graph.toString());
 256                 graphSeen = true;
 257             }
 258             // Reverse list such that inner method comes after outer method.
 259             Collections.reverse(result);
 260             if (!graphSeen) {
 261                 /*
 262                  * The graph isn't in any context but is being processed within another graph so add
 263                  * it to the end of the scopes.
 264                  */
 265                 if (asJavaMethod(graph) != null) {
 266                     addMethodContext(result, graph, lastMethodOrGraph);
 267                 } else {
 268                     result.add(graph.toString());
 269                 }
 270             }
 271             inlineContextMap.put(graph, result);
 272         }
 273         return result;
 274     }
 275 
 276     private static void addMethodContext(List<String> result, Object o, Object lastMethodOrGraph) {
 277         JavaMethod method = asJavaMethod(o);
 278         if (method != null) {
 279             /*
 280              * Include the current method in the context if there was no previous JavaMethod or
 281              * JavaMethodContext or if the method is different or if the method is the same but it
 282              * comes from two different graphs. This ensures that recursive call patterns are
 283              * handled properly.
 284              */
 285             if (lastMethodOrGraph == null || asJavaMethod(lastMethodOrGraph) == null || !asJavaMethod(lastMethodOrGraph).equals(method) ||
 286                             (lastMethodOrGraph != o && lastMethodOrGraph instanceof Graph && o instanceof Graph)) {
 287                 result.add(method.format("%H.%n(%p)"));
 288             } else {
 289                 /*
 290                  * This prevents multiple adjacent method context objects for the same method from
 291                  * resulting in multiple IGV tree levels. This works on the assumption that real
 292                  * inlining debug scopes will have a graph context object between the inliner and
 293                  * inlinee context objects.
 294                  */
 295             }
 296         }
 297     }
 298 
 299     private void openScope(DebugContext debug, String name, int inlineDepth, Map<Object, Object> properties) {
 300         try {
 301             Map<Object, Object> props = properties;
 302             if (inlineDepth == 0) {
 303                 /* Include some VM specific properties at the root. */
 304                 if (props == null) {
 305                     props = new HashMap<>();
 306                 }
 307                 props.put("jvmArguments", jvmArguments);
 308                 if (sunJavaCommand != null) {
 309                     props.put("sun.java.command", sunJavaCommand);
 310                 }
 311                 props.put("date", new Date().toString());
 312             }
 313             printer.beginGroup(debug, name, name, debug.contextLookup(ResolvedJavaMethod.class), -1, props);
 314         } catch (IOException e) {
 315             handleException(debug, e);
 316         }
 317     }
 318 
 319     private void closeScope(DebugContext debug, int inlineDepth) {
 320         dumpIds[inlineDepth] = 0;
 321         try {
 322             if (printer != null) {
 323                 printer.endGroup();
 324             }
 325         } catch (IOException e) {
 326             handleException(debug, e);
 327         }
 328     }
 329 
 330     @Override
 331     public void close() {
 332         if (previousInlineContext != null) {
 333             for (int inlineDepth = 0; inlineDepth < previousInlineContext.size(); inlineDepth++) {
 334                 closeScope(null, inlineDepth);
 335             }
 336         }
 337         if (printer != null) {
 338             printer.close();
 339             printer = null;
 340         }
 341     }
 342 }