1 /* 2 * Copyright (c) 2015, 2016, 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 org.graalvm.compiler.core.common.GraalOptions.OptAssumptions; 26 import static org.graalvm.compiler.nodes.graphbuilderconf.IntrinsicContext.CompilationContext.ROOT_COMPILATION; 27 28 import java.io.ByteArrayOutputStream; 29 import java.io.PrintStream; 30 import java.util.Collections; 31 import java.util.Formattable; 32 import java.util.Formatter; 33 import java.util.List; 34 35 import org.graalvm.compiler.api.runtime.GraalJVMCICompiler; 36 import org.graalvm.compiler.bytecode.Bytecode; 37 import org.graalvm.compiler.code.CompilationResult; 38 import org.graalvm.compiler.core.GraalCompiler; 39 import org.graalvm.compiler.core.common.CompilationIdentifier; 40 import org.graalvm.compiler.core.common.util.CompilationAlarm; 41 import org.graalvm.compiler.debug.DebugHandlersFactory; 42 import org.graalvm.compiler.debug.DebugContext; 43 import org.graalvm.compiler.debug.DebugContext.Activation; 44 import org.graalvm.compiler.debug.DebugOptions; 45 import org.graalvm.compiler.hotspot.CompilationCounters.Options; 46 import org.graalvm.compiler.hotspot.meta.HotSpotProviders; 47 import org.graalvm.compiler.hotspot.phases.OnStackReplacementPhase; 48 import org.graalvm.compiler.java.GraphBuilderPhase; 49 import org.graalvm.compiler.lir.asm.CompilationResultBuilderFactory; 50 import org.graalvm.compiler.lir.phases.LIRSuites; 51 import org.graalvm.compiler.nodes.StructuredGraph; 52 import org.graalvm.compiler.nodes.StructuredGraph.AllowAssumptions; 53 import org.graalvm.compiler.nodes.graphbuilderconf.GraphBuilderConfiguration; 54 import org.graalvm.compiler.nodes.graphbuilderconf.GraphBuilderConfiguration.Plugins; 55 import org.graalvm.compiler.nodes.graphbuilderconf.IntrinsicContext; 56 import org.graalvm.compiler.nodes.spi.Replacements; 57 import org.graalvm.compiler.options.OptionValues; 58 import org.graalvm.compiler.phases.OptimisticOptimizations; 59 import org.graalvm.compiler.phases.OptimisticOptimizations.Optimization; 60 import org.graalvm.compiler.phases.PhaseSuite; 61 import org.graalvm.compiler.phases.tiers.HighTierContext; 62 import org.graalvm.compiler.phases.tiers.Suites; 63 import org.graalvm.compiler.printer.GraalDebugHandlersFactory; 64 65 import jdk.vm.ci.code.CompilationRequest; 66 import jdk.vm.ci.code.CompilationRequestResult; 67 import jdk.vm.ci.hotspot.HotSpotCompilationRequest; 68 import jdk.vm.ci.hotspot.HotSpotCompilationRequestResult; 69 import jdk.vm.ci.hotspot.HotSpotJVMCIRuntimeProvider; 70 import jdk.vm.ci.meta.DefaultProfilingInfo; 71 import jdk.vm.ci.meta.JavaMethod; 72 import jdk.vm.ci.meta.ProfilingInfo; 73 import jdk.vm.ci.meta.ResolvedJavaMethod; 74 import jdk.vm.ci.meta.SpeculationLog; 75 import jdk.vm.ci.meta.TriState; 76 import jdk.vm.ci.runtime.JVMCICompiler; 77 78 public class HotSpotGraalCompiler implements GraalJVMCICompiler { 79 80 private final HotSpotJVMCIRuntimeProvider jvmciRuntime; 81 private final HotSpotGraalRuntimeProvider graalRuntime; 82 private final CompilationCounters compilationCounters; 83 private final BootstrapWatchDog bootstrapWatchDog; 84 private List<DebugHandlersFactory> factories; 85 86 HotSpotGraalCompiler(HotSpotJVMCIRuntimeProvider jvmciRuntime, HotSpotGraalRuntimeProvider graalRuntime, OptionValues options) { 87 this.jvmciRuntime = jvmciRuntime; 88 this.graalRuntime = graalRuntime; 89 // It is sufficient to have one compilation counter object per Graal compiler object. 90 this.compilationCounters = Options.CompilationCountLimit.getValue(options) > 0 ? new CompilationCounters(options) : null; 91 this.bootstrapWatchDog = graalRuntime.isBootstrapping() && !DebugOptions.BootstrapInitializeOnly.getValue(options) ? BootstrapWatchDog.maybeCreate(graalRuntime) : null; 92 } 93 94 public List<DebugHandlersFactory> getDebugHandlersFactories() { 95 if (factories == null) { 96 factories = Collections.singletonList(new GraalDebugHandlersFactory(graalRuntime.getHostProviders().getSnippetReflection())); 97 } 98 return factories; 99 } 100 101 @Override 102 public HotSpotGraalRuntimeProvider getGraalRuntime() { 103 return graalRuntime; 104 } 105 106 @Override 107 public CompilationRequestResult compileMethod(CompilationRequest request) { 108 return compileMethod(request, true); 109 } 110 111 @SuppressWarnings("try") 112 CompilationRequestResult compileMethod(CompilationRequest request, boolean installAsDefault) { 113 if (graalRuntime.isShutdown()) { 114 return HotSpotCompilationRequestResult.failure(String.format("Shutdown entered"), false); 115 } 116 117 ResolvedJavaMethod method = request.getMethod(); 118 OptionValues options = graalRuntime.getOptions(method); 119 120 if (graalRuntime.isBootstrapping()) { 121 if (DebugOptions.BootstrapInitializeOnly.getValue(options)) { 122 return HotSpotCompilationRequestResult.failure(String.format("Skip compilation because %s is enabled", DebugOptions.BootstrapInitializeOnly.getName()), true); 123 } 124 if (bootstrapWatchDog != null) { 125 if (bootstrapWatchDog.hitCriticalCompilationRateOrTimeout()) { 126 // Drain the compilation queue to expedite completion of the bootstrap 127 return HotSpotCompilationRequestResult.failure("hit critical bootstrap compilation rate or timeout", true); 128 } 129 } 130 } 131 HotSpotCompilationRequest hsRequest = (HotSpotCompilationRequest) request; 132 try (CompilationWatchDog w1 = CompilationWatchDog.watch(method, hsRequest.getId(), options); 133 BootstrapWatchDog.Watch w2 = bootstrapWatchDog == null ? null : bootstrapWatchDog.watch(request); 134 CompilationAlarm alarm = CompilationAlarm.trackCompilationPeriod(options);) { 135 if (compilationCounters != null) { 136 compilationCounters.countCompilation(method); 137 } 138 CompilationTask task = new CompilationTask(jvmciRuntime, this, hsRequest, true, installAsDefault, options); 139 CompilationRequestResult r = null; 140 try (DebugContext debug = graalRuntime.openDebugContext(options, task.getCompilationIdentifier(), method, getDebugHandlersFactories()); 141 Activation a = debug.activate()) { 142 r = task.runCompilation(debug); 143 } 144 assert r != null; 145 return r; 146 } 147 } 148 149 public CompilationResult compile(ResolvedJavaMethod method, int entryBCI, boolean useProfilingInfo, CompilationIdentifier compilationId, OptionValues options, DebugContext debug) { 150 HotSpotBackend backend = graalRuntime.getHostBackend(); 151 HotSpotProviders providers = backend.getProviders(); 152 final boolean isOSR = entryBCI != JVMCICompiler.INVOCATION_ENTRY_BCI; 153 StructuredGraph graph = method.isNative() || isOSR ? null : getIntrinsicGraph(method, providers, compilationId, options, debug); 154 155 if (graph == null) { 156 SpeculationLog speculationLog = method.getSpeculationLog(); 157 if (speculationLog != null) { 158 speculationLog.collectFailedSpeculations(); 159 } 160 graph = new StructuredGraph.Builder(options, debug, AllowAssumptions.ifTrue(OptAssumptions.getValue(options))).method(method).entryBCI(entryBCI).speculationLog( 161 speculationLog).useProfilingInfo(useProfilingInfo).compilationId(compilationId).build(); 162 } 163 164 Suites suites = getSuites(providers, options); 165 LIRSuites lirSuites = getLIRSuites(providers, options); 166 ProfilingInfo profilingInfo = useProfilingInfo ? method.getProfilingInfo(!isOSR, isOSR) : DefaultProfilingInfo.get(TriState.FALSE); 167 OptimisticOptimizations optimisticOpts = getOptimisticOpts(profilingInfo, options); 168 169 /* 170 * Cut off never executed code profiles if there is code, e.g. after the osr loop, that is 171 * never executed. 172 */ 173 if (isOSR && !OnStackReplacementPhase.Options.DeoptAfterOSR.getValue(options)) { 174 optimisticOpts.remove(Optimization.RemoveNeverExecutedCode); 175 } 176 CompilationResult result = new CompilationResult(); 177 result.setEntryBCI(entryBCI); 178 boolean shouldDebugNonSafepoints = providers.getCodeCache().shouldDebugNonSafepoints(); 179 PhaseSuite<HighTierContext> graphBuilderSuite = configGraphBuilderSuite(providers.getSuites().getDefaultGraphBuilderSuite(), shouldDebugNonSafepoints, isOSR); 180 GraalCompiler.compileGraph(graph, method, providers, backend, graphBuilderSuite, optimisticOpts, profilingInfo, suites, lirSuites, result, CompilationResultBuilderFactory.Default); 181 182 if (!isOSR && useProfilingInfo) { 183 ProfilingInfo profile = profilingInfo; 184 profile.setCompilerIRSize(StructuredGraph.class, graph.getNodeCount()); 185 } 186 187 return result; 188 } 189 190 /** 191 * Gets a graph produced from the intrinsic for a given method that can be compiled and 192 * installed for the method. 193 * 194 * @param method 195 * @param compilationId 196 * @param options 197 * @param debug 198 * @return an intrinsic graph that can be compiled and installed for {@code method} or null 199 */ 200 @SuppressWarnings("try") 201 public StructuredGraph getIntrinsicGraph(ResolvedJavaMethod method, HotSpotProviders providers, CompilationIdentifier compilationId, OptionValues options, DebugContext debug) { 202 Replacements replacements = providers.getReplacements(); 203 Bytecode subst = replacements.getSubstitutionBytecode(method); 204 if (subst != null) { 205 ResolvedJavaMethod substMethod = subst.getMethod(); 206 assert !substMethod.equals(method); 207 StructuredGraph graph = new StructuredGraph.Builder(options, debug, AllowAssumptions.YES).method(substMethod).compilationId(compilationId).build(); 208 try (DebugContext.Scope scope = debug.scope("GetIntrinsicGraph", graph)) { 209 Plugins plugins = new Plugins(providers.getGraphBuilderPlugins()); 210 GraphBuilderConfiguration config = GraphBuilderConfiguration.getSnippetDefault(plugins); 211 IntrinsicContext initialReplacementContext = new IntrinsicContext(method, substMethod, subst.getOrigin(), ROOT_COMPILATION); 212 new GraphBuilderPhase.Instance(providers.getMetaAccess(), providers.getStampProvider(), providers.getConstantReflection(), providers.getConstantFieldProvider(), config, 213 OptimisticOptimizations.NONE, initialReplacementContext).apply(graph); 214 assert !graph.isFrozen(); 215 return graph; 216 } catch (Throwable e) { 217 debug.handle(e); 218 } 219 } 220 return null; 221 } 222 223 protected OptimisticOptimizations getOptimisticOpts(ProfilingInfo profilingInfo, OptionValues options) { 224 return new OptimisticOptimizations(profilingInfo, options); 225 } 226 227 protected Suites getSuites(HotSpotProviders providers, OptionValues options) { 228 return providers.getSuites().getDefaultSuites(options); 229 } 230 231 protected LIRSuites getLIRSuites(HotSpotProviders providers, OptionValues options) { 232 return providers.getSuites().getDefaultLIRSuites(options); 233 } 234 235 /** 236 * Reconfigures a given graph builder suite (GBS) if one of the given GBS parameter values is 237 * not the default. 238 * 239 * @param suite the graph builder suite 240 * @param shouldDebugNonSafepoints specifies if extra debug info should be generated (default is 241 * false) 242 * @param isOSR specifies if extra OSR-specific post-processing is required (default is false) 243 * @return a new suite derived from {@code suite} if any of the GBS parameters did not have a 244 * default value otherwise {@code suite} 245 */ 246 protected PhaseSuite<HighTierContext> configGraphBuilderSuite(PhaseSuite<HighTierContext> suite, boolean shouldDebugNonSafepoints, boolean isOSR) { 247 if (shouldDebugNonSafepoints || isOSR) { 248 PhaseSuite<HighTierContext> newGbs = suite.copy(); 249 250 if (shouldDebugNonSafepoints) { 251 GraphBuilderPhase graphBuilderPhase = (GraphBuilderPhase) newGbs.findPhase(GraphBuilderPhase.class).previous(); 252 GraphBuilderConfiguration graphBuilderConfig = graphBuilderPhase.getGraphBuilderConfig(); 253 graphBuilderConfig = graphBuilderConfig.withNodeSourcePosition(true); 254 GraphBuilderPhase newGraphBuilderPhase = new GraphBuilderPhase(graphBuilderConfig); 255 newGbs.findPhase(GraphBuilderPhase.class).set(newGraphBuilderPhase); 256 } 257 if (isOSR) { 258 // We must not clear non liveness for OSR compilations. 259 GraphBuilderPhase graphBuilderPhase = (GraphBuilderPhase) newGbs.findPhase(GraphBuilderPhase.class).previous(); 260 GraphBuilderConfiguration graphBuilderConfig = graphBuilderPhase.getGraphBuilderConfig(); 261 GraphBuilderPhase newGraphBuilderPhase = new GraphBuilderPhase(graphBuilderConfig); 262 newGbs.findPhase(GraphBuilderPhase.class).set(newGraphBuilderPhase); 263 newGbs.appendPhase(new OnStackReplacementPhase()); 264 } 265 return newGbs; 266 } 267 return suite; 268 } 269 270 /** 271 * Converts {@code method} to a String with {@link JavaMethod#format(String)} and the format 272 * string {@code "%H.%n(%p)"}. 273 */ 274 static String str(JavaMethod method) { 275 return method.format("%H.%n(%p)"); 276 } 277 278 /** 279 * Wraps {@code obj} in a {@link Formatter} that standardizes formatting for certain objects. 280 */ 281 static Formattable fmt(Object obj) { 282 return new Formattable() { 283 @Override 284 public void formatTo(Formatter buf, int flags, int width, int precision) { 285 if (obj instanceof Throwable) { 286 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 287 ((Throwable) obj).printStackTrace(new PrintStream(baos)); 288 buf.format("%s", baos.toString()); 289 } else if (obj instanceof StackTraceElement[]) { 290 for (StackTraceElement e : (StackTraceElement[]) obj) { 291 buf.format("\t%s%n", e); 292 } 293 } else if (obj instanceof JavaMethod) { 294 buf.format("%s", str((JavaMethod) obj)); 295 } else { 296 buf.format("%s", obj); 297 } 298 } 299 }; 300 } 301 }