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