1 /*
   2  * Copyright (c) 2012, 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 
  24 
  25 package org.graalvm.compiler.hotspot;
  26 
  27 import static org.graalvm.compiler.core.CompilationWrapper.ExceptionAction.Diagnose;
  28 import static org.graalvm.compiler.core.CompilationWrapper.ExceptionAction.ExitVM;
  29 import static org.graalvm.compiler.core.GraalCompilerOptions.CompilationBailoutAction;
  30 import static org.graalvm.compiler.core.GraalCompilerOptions.CompilationFailureAction;
  31 import static org.graalvm.compiler.core.phases.HighTier.Options.Inline;
  32 import static org.graalvm.compiler.java.BytecodeParserOptions.InlineDuringParsing;
  33 
  34 import java.util.List;
  35 
  36 import jdk.internal.vm.compiler.collections.EconomicMap;
  37 import org.graalvm.compiler.api.replacements.SnippetReflectionProvider;
  38 import org.graalvm.compiler.code.CompilationResult;
  39 import org.graalvm.compiler.core.CompilationPrinter;
  40 import org.graalvm.compiler.core.CompilationWrapper;
  41 import org.graalvm.compiler.core.common.CompilationIdentifier;
  42 import org.graalvm.compiler.debug.Assertions;
  43 import org.graalvm.compiler.debug.CounterKey;
  44 import org.graalvm.compiler.debug.DebugCloseable;
  45 import org.graalvm.compiler.debug.DebugContext;
  46 import org.graalvm.compiler.debug.DebugDumpScope;
  47 import org.graalvm.compiler.debug.GraalError;
  48 import org.graalvm.compiler.debug.TimerKey;
  49 import org.graalvm.compiler.options.EnumOptionKey;
  50 import org.graalvm.compiler.options.OptionKey;
  51 import org.graalvm.compiler.options.OptionValues;
  52 import org.graalvm.compiler.printer.GraalDebugHandlersFactory;
  53 
  54 import jdk.vm.ci.code.BailoutException;
  55 import jdk.vm.ci.code.CodeCacheProvider;
  56 import jdk.vm.ci.hotspot.EventProvider;
  57 import jdk.vm.ci.hotspot.HotSpotCompilationRequest;
  58 import jdk.vm.ci.hotspot.HotSpotCompilationRequestResult;
  59 import jdk.vm.ci.hotspot.HotSpotInstalledCode;
  60 import jdk.vm.ci.hotspot.HotSpotJVMCICompilerFactory;
  61 import jdk.vm.ci.hotspot.HotSpotJVMCIRuntime;
  62 import jdk.vm.ci.hotspot.HotSpotNmethod;
  63 import jdk.vm.ci.hotspot.HotSpotResolvedJavaMethod;
  64 import jdk.vm.ci.runtime.JVMCICompiler;
  65 import jdk.vm.ci.services.JVMCIServiceLocator;
  66 
  67 public class CompilationTask {
  68 
  69     private static final EventProvider eventProvider;
  70 
  71     static {
  72         List<EventProvider> providers = JVMCIServiceLocator.getProviders(EventProvider.class);
  73         if (providers.size() > 1) {
  74             throw new GraalError("Multiple %s providers found: %s", EventProvider.class.getName(), providers);
  75         } else if (providers.isEmpty()) {
  76             eventProvider = EventProvider.createEmptyEventProvider();
  77         } else {
  78             eventProvider = providers.get(0);
  79         }
  80     }
  81 
  82     private final HotSpotJVMCIRuntime jvmciRuntime;
  83 
  84     private final HotSpotGraalCompiler compiler;
  85     private final HotSpotCompilationIdentifier compilationId;
  86 
  87     private HotSpotInstalledCode installedCode;
  88 
  89     /**
  90      * Specifies whether the compilation result is installed as the
  91      * {@linkplain HotSpotNmethod#isDefault() default} nmethod for the compiled method.
  92      */
  93     private final boolean installAsDefault;
  94 
  95     private final boolean useProfilingInfo;
  96     private final OptionValues options;
  97 
  98     final class HotSpotCompilationWrapper extends CompilationWrapper<HotSpotCompilationRequestResult> {
  99         private final EventProvider.CompilationEvent compilationEvent;
 100         CompilationResult result;
 101 
 102         HotSpotCompilationWrapper(EventProvider.CompilationEvent compilationEvent) {
 103             super(compiler.getGraalRuntime().getOutputDirectory(), compiler.getGraalRuntime().getCompilationProblemsPerAction());
 104             this.compilationEvent = compilationEvent;
 105         }
 106 
 107         @Override
 108         protected DebugContext createRetryDebugContext(OptionValues retryOptions) {
 109             SnippetReflectionProvider snippetReflection = compiler.getGraalRuntime().getHostProviders().getSnippetReflection();
 110             return DebugContext.create(retryOptions, new GraalDebugHandlersFactory(snippetReflection));
 111         }
 112 
 113         @Override
 114         public String toString() {
 115             return getMethod().format("%H.%n(%p)");
 116         }
 117 
 118         @Override
 119         protected HotSpotCompilationRequestResult handleException(Throwable t) {
 120             if (t instanceof BailoutException) {
 121                 BailoutException bailout = (BailoutException) t;
 122                 /*
 123                  * Handling of permanent bailouts: Permanent bailouts that can happen for example
 124                  * due to unsupported unstructured control flow in the bytecodes of a method must
 125                  * not be retried. Hotspot compile broker will ensure that no recompilation at the
 126                  * given tier will happen if retry is false.
 127                  */
 128                 return HotSpotCompilationRequestResult.failure(bailout.getMessage(), !bailout.isPermanent());
 129             }
 130             // Log a failure event.
 131             EventProvider.CompilerFailureEvent event = eventProvider.newCompilerFailureEvent();
 132             if (event.shouldWrite()) {
 133                 event.setCompileId(getId());
 134                 event.setMessage(t.getMessage());
 135                 event.commit();
 136             }
 137 
 138             /*
 139              * Treat random exceptions from the compiler as indicating a problem compiling this
 140              * method. Report the result of toString instead of getMessage to ensure that the
 141              * exception type is included in the output in case there's no detail mesage.
 142              */
 143             return HotSpotCompilationRequestResult.failure(t.toString(), false);
 144         }
 145 
 146         @Override
 147         protected ExceptionAction lookupAction(OptionValues values, EnumOptionKey<ExceptionAction> actionKey, Throwable cause) {
 148             // Respect current action if it has been explicitly set.
 149             if (!actionKey.hasBeenSet(values)) {
 150                 if (actionKey == CompilationFailureAction) {
 151                     // Automatically exit on non-bailout during bootstrap
 152                     // or when assertions are enabled.
 153                     if (Assertions.assertionsEnabled() || compiler.getGraalRuntime().isBootstrapping()) {
 154                         return ExitVM;
 155                     }
 156                 } else if (actionKey == CompilationBailoutAction && ((BailoutException) cause).isPermanent()) {
 157                     // Get more info for permanent bailouts during bootstrap
 158                     // or when assertions are enabled.
 159                     assert CompilationBailoutAction.getDefaultValue() == ExceptionAction.Silent;
 160                     if (Assertions.assertionsEnabled() || compiler.getGraalRuntime().isBootstrapping()) {
 161                         return Diagnose;
 162                     }
 163                 }
 164             }
 165             return super.lookupAction(values, actionKey, cause);
 166         }
 167 
 168         @SuppressWarnings("try")
 169         @Override
 170         protected HotSpotCompilationRequestResult performCompilation(DebugContext debug) {
 171             HotSpotResolvedJavaMethod method = getMethod();
 172             int entryBCI = getEntryBCI();
 173             final boolean isOSR = entryBCI != JVMCICompiler.INVOCATION_ENTRY_BCI;
 174             CompilationStatistics stats = CompilationStatistics.create(options, method, isOSR);
 175 
 176             final CompilationPrinter printer = CompilationPrinter.begin(options, compilationId, method, entryBCI);
 177 
 178             try (DebugContext.Scope s = debug.scope("Compiling", new DebugDumpScope(getIdString(), true))) {
 179                 // Begin the compilation event.
 180                 compilationEvent.begin();
 181                 result = compiler.compile(method, entryBCI, useProfilingInfo, compilationId, options, debug);
 182             } catch (Throwable e) {
 183                 throw debug.handle(e);
 184             } finally {
 185                 // End the compilation event.
 186                 compilationEvent.end();
 187             }
 188 
 189             if (result != null) {
 190                 try (DebugCloseable b = CodeInstallationTime.start(debug)) {
 191                     installMethod(debug, result);
 192                 }
 193                 // Installation is included in compilation time and memory usage reported by printer
 194                 printer.finish(result);
 195             }
 196             stats.finish(method, installedCode);
 197             if (result != null) {
 198                 return HotSpotCompilationRequestResult.success(result.getBytecodeSize() - method.getCodeSize());
 199             }
 200             return null;
 201         }
 202 
 203     }
 204 
 205     public CompilationTask(HotSpotJVMCIRuntime jvmciRuntime, HotSpotGraalCompiler compiler, HotSpotCompilationRequest request, boolean useProfilingInfo, boolean installAsDefault,
 206                     OptionValues options) {
 207         this.jvmciRuntime = jvmciRuntime;
 208         this.compiler = compiler;
 209         this.compilationId = new HotSpotCompilationIdentifier(request);
 210         this.useProfilingInfo = useProfilingInfo;
 211         this.installAsDefault = installAsDefault;
 212 
 213         /*
 214          * Disable inlining if HotSpot has it disabled unless it's been explicitly set in Graal.
 215          */
 216         HotSpotGraalRuntimeProvider graalRuntime = compiler.getGraalRuntime();
 217         GraalHotSpotVMConfig config = graalRuntime.getVMConfig();
 218         OptionValues newOptions = options;
 219         if (!config.inline) {
 220             EconomicMap<OptionKey<?>, Object> m = OptionValues.newOptionMap();
 221             if (Inline.getValue(options) && !Inline.hasBeenSet(options)) {
 222                 m.put(Inline, false);
 223             }
 224             if (InlineDuringParsing.getValue(options) && !InlineDuringParsing.hasBeenSet(options)) {
 225                 m.put(InlineDuringParsing, false);
 226             }
 227             if (!m.isEmpty()) {
 228                 newOptions = new OptionValues(options, m);
 229             }
 230         }
 231         this.options = newOptions;
 232     }
 233 
 234     public HotSpotResolvedJavaMethod getMethod() {
 235         return getRequest().getMethod();
 236     }
 237 
 238     CompilationIdentifier getCompilationIdentifier() {
 239         return compilationId;
 240     }
 241 
 242     /**
 243      * Returns the HotSpot id of this compilation.
 244      *
 245      * @return HotSpot compile id
 246      */
 247     public int getId() {
 248         return getRequest().getId();
 249     }
 250 
 251     public int getEntryBCI() {
 252         return getRequest().getEntryBCI();
 253     }
 254 
 255     /**
 256      * @return the compilation id plus a trailing '%' if the compilation is an OSR to match
 257      *         PrintCompilation style output
 258      */
 259     public String getIdString() {
 260         if (getEntryBCI() != JVMCICompiler.INVOCATION_ENTRY_BCI) {
 261             return getId() + "%";
 262         } else {
 263             return Integer.toString(getId());
 264         }
 265     }
 266 
 267     public HotSpotInstalledCode getInstalledCode() {
 268         return installedCode;
 269     }
 270 
 271     /**
 272      * Time spent in compilation.
 273      */
 274     private static final TimerKey CompilationTime = DebugContext.timer("CompilationTime").doc("Time spent in compilation and code installation.");
 275 
 276     /**
 277      * Counts the number of compiled {@linkplain CompilationResult#getBytecodeSize() bytecodes}.
 278      */
 279     private static final CounterKey CompiledBytecodes = DebugContext.counter("CompiledBytecodes");
 280 
 281     /**
 282      * Counts the number of compiled {@linkplain CompilationResult#getBytecodeSize() bytecodes} for
 283      * which {@linkplain CompilationResult#getTargetCode()} code was installed.
 284      */
 285     private static final CounterKey CompiledAndInstalledBytecodes = DebugContext.counter("CompiledAndInstalledBytecodes");
 286 
 287     /**
 288      * Counts the number of installed {@linkplain CompilationResult#getTargetCodeSize()} bytes.
 289      */
 290     private static final CounterKey InstalledCodeSize = DebugContext.counter("InstalledCodeSize");
 291 
 292     /**
 293      * Time spent in code installation.
 294      */
 295     public static final TimerKey CodeInstallationTime = DebugContext.timer("CodeInstallation");
 296 
 297     public HotSpotCompilationRequestResult runCompilation() {
 298         SnippetReflectionProvider snippetReflection = compiler.getGraalRuntime().getHostProviders().getSnippetReflection();
 299         try (DebugContext debug = DebugContext.create(options, new GraalDebugHandlersFactory(snippetReflection))) {
 300             return runCompilation(debug);
 301         }
 302     }
 303 
 304     @SuppressWarnings("try")
 305     public HotSpotCompilationRequestResult runCompilation(DebugContext debug) {
 306         HotSpotGraalRuntimeProvider graalRuntime = compiler.getGraalRuntime();
 307         GraalHotSpotVMConfig config = graalRuntime.getVMConfig();
 308         int entryBCI = getEntryBCI();
 309         boolean isOSR = entryBCI != JVMCICompiler.INVOCATION_ENTRY_BCI;
 310         HotSpotResolvedJavaMethod method = getMethod();
 311 
 312         // Log a compilation event.
 313         EventProvider.CompilationEvent compilationEvent = eventProvider.newCompilationEvent();
 314 
 315         if (installAsDefault) {
 316             // If there is already compiled code for this method on our level we simply return.
 317             // JVMCI compiles are always at the highest compile level, even in non-tiered mode so we
 318             // only need to check for that value.
 319             if (method.hasCodeAtLevel(entryBCI, config.compilationLevelFullOptimization)) {
 320                 return HotSpotCompilationRequestResult.failure("Already compiled", false);
 321             }
 322             if (HotSpotGraalCompilerFactory.checkGraalCompileOnlyFilter(method.getDeclaringClass().toJavaName(), method.getName(), method.getSignature().toString(),
 323                             HotSpotJVMCICompilerFactory.CompilationLevel.FullOptimization) != HotSpotJVMCICompilerFactory.CompilationLevel.FullOptimization) {
 324                 return HotSpotCompilationRequestResult.failure("GraalCompileOnly excluded", false);
 325             }
 326         }
 327 
 328         HotSpotCompilationWrapper compilation = new HotSpotCompilationWrapper(compilationEvent);
 329         try (DebugCloseable a = CompilationTime.start(debug)) {
 330             return compilation.run(debug);
 331         } finally {
 332             try {
 333                 int compiledBytecodes = 0;
 334                 int codeSize = 0;
 335 
 336                 if (compilation.result != null) {
 337                     compiledBytecodes = compilation.result.getBytecodeSize();
 338                     CompiledBytecodes.add(debug, compiledBytecodes);
 339                     if (installedCode != null) {
 340                         codeSize = installedCode.getSize();
 341                         CompiledAndInstalledBytecodes.add(debug, compiledBytecodes);
 342                         InstalledCodeSize.add(debug, codeSize);
 343                     }
 344                 }
 345 
 346                 // Log a compilation event.
 347                 if (compilationEvent.shouldWrite()) {
 348                     compilationEvent.setMethod(method.format("%H.%n(%p)"));
 349                     compilationEvent.setCompileId(getId());
 350                     compilationEvent.setCompileLevel(config.compilationLevelFullOptimization);
 351                     compilationEvent.setSucceeded(compilation.result != null && installedCode != null);
 352                     compilationEvent.setIsOsr(isOSR);
 353                     compilationEvent.setCodeSize(codeSize);
 354                     compilationEvent.setInlinedBytes(compiledBytecodes);
 355                     compilationEvent.commit();
 356                 }
 357             } catch (Throwable t) {
 358                 return compilation.handleException(t);
 359             }
 360         }
 361     }
 362 
 363     @SuppressWarnings("try")
 364     private void installMethod(DebugContext debug, final CompilationResult compResult) {
 365         final CodeCacheProvider codeCache = jvmciRuntime.getHostJVMCIBackend().getCodeCache();
 366         HotSpotBackend backend = compiler.getGraalRuntime().getHostBackend();
 367         installedCode = null;
 368         Object[] context = {new DebugDumpScope(getIdString(), true), codeCache, getMethod(), compResult};
 369         try (DebugContext.Scope s = debug.scope("CodeInstall", context)) {
 370             installedCode = (HotSpotInstalledCode) backend.createInstalledCode(debug, getRequest().getMethod(), getRequest(), compResult,
 371                             getRequest().getMethod().getSpeculationLog(), null, installAsDefault, context);
 372         } catch (Throwable e) {
 373             throw debug.handle(e);
 374         }
 375     }
 376 
 377     @Override
 378     public String toString() {
 379         return "Compilation[id=" + getId() + ", " + getMethod().format("%H.%n(%p)") + (getEntryBCI() == JVMCICompiler.INVOCATION_ENTRY_BCI ? "" : "@" + getEntryBCI()) + "]";
 380     }
 381 
 382     private HotSpotCompilationRequest getRequest() {
 383         return compilationId.getRequest();
 384     }
 385 }