1 /*
   2  * Copyright (c) 2009, 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.core.target;
  26 
  27 import java.util.ArrayList;
  28 
  29 import org.graalvm.compiler.code.CompilationResult;
  30 import org.graalvm.compiler.core.common.CompilationIdentifier;
  31 import org.graalvm.compiler.core.common.LIRKind;
  32 import org.graalvm.compiler.core.common.alloc.RegisterAllocationConfig;
  33 import org.graalvm.compiler.core.common.spi.ForeignCallDescriptor;
  34 import org.graalvm.compiler.core.common.spi.ForeignCallsProvider;
  35 import org.graalvm.compiler.core.gen.LIRCompilerBackend;
  36 import org.graalvm.compiler.debug.DebugContext;
  37 import org.graalvm.compiler.lir.asm.CompilationResultBuilderFactory;
  38 import org.graalvm.compiler.lir.phases.LIRSuites;
  39 import org.graalvm.compiler.nodes.StructuredGraph;
  40 import org.graalvm.compiler.options.OptionValues;
  41 import org.graalvm.compiler.phases.tiers.SuitesProvider;
  42 import org.graalvm.compiler.phases.tiers.TargetProvider;
  43 import org.graalvm.compiler.phases.util.Providers;
  44 
  45 import jdk.vm.ci.code.BailoutException;
  46 import jdk.vm.ci.code.CodeCacheProvider;
  47 import jdk.vm.ci.code.CompilationRequest;
  48 import jdk.vm.ci.code.CompiledCode;
  49 import jdk.vm.ci.code.InstalledCode;
  50 import jdk.vm.ci.code.RegisterConfig;
  51 import jdk.vm.ci.code.TargetDescription;
  52 import jdk.vm.ci.code.ValueKindFactory;
  53 import jdk.vm.ci.meta.ConstantReflectionProvider;
  54 import jdk.vm.ci.meta.JavaKind;
  55 import jdk.vm.ci.meta.MetaAccessProvider;
  56 import jdk.vm.ci.meta.ResolvedJavaMethod;
  57 
  58 /**
  59  * Represents a compiler backend for Graal.
  60  */
  61 public abstract class Backend implements TargetProvider, ValueKindFactory<LIRKind> {
  62 
  63     private final Providers providers;
  64     private final ArrayList<CodeInstallationTaskFactory> codeInstallationTaskFactories;
  65 
  66     public static final ForeignCallDescriptor ARITHMETIC_FREM = new ForeignCallDescriptor("arithmeticFrem", float.class, float.class, float.class);
  67     public static final ForeignCallDescriptor ARITHMETIC_DREM = new ForeignCallDescriptor("arithmeticDrem", double.class, double.class, double.class);
  68 
  69     protected Backend(Providers providers) {
  70         this.providers = providers;
  71         this.codeInstallationTaskFactories = new ArrayList<>();
  72     }
  73 
  74     public synchronized void addCodeInstallationTask(CodeInstallationTaskFactory factory) {
  75         this.codeInstallationTaskFactories.add(factory);
  76     }
  77 
  78     public Providers getProviders() {
  79         return providers;
  80     }
  81 
  82     public CodeCacheProvider getCodeCache() {
  83         return providers.getCodeCache();
  84     }
  85 
  86     public MetaAccessProvider getMetaAccess() {
  87         return providers.getMetaAccess();
  88     }
  89 
  90     public ConstantReflectionProvider getConstantReflection() {
  91         return providers.getConstantReflection();
  92     }
  93 
  94     public ForeignCallsProvider getForeignCalls() {
  95         return providers.getForeignCalls();
  96     }
  97 
  98     public abstract SuitesProvider getSuites();
  99 
 100     @Override
 101     public TargetDescription getTarget() {
 102         return providers.getCodeCache().getTarget();
 103     }
 104 
 105     @Override
 106     public LIRKind getValueKind(JavaKind javaKind) {
 107         return LIRKind.fromJavaKind(getTarget().arch, javaKind);
 108     }
 109 
 110     /**
 111      * Creates a new configuration for register allocation.
 112      *
 113      * @param allocationRestrictedTo if not {@code null}, register allocation will be restricted to
 114      *            registers whose names appear in this array
 115      */
 116     public abstract RegisterAllocationConfig newRegisterAllocationConfig(RegisterConfig registerConfig, String[] allocationRestrictedTo);
 117 
 118     /**
 119      * Turns a Graal {@link CompilationResult} into a {@link CompiledCode} object that can be passed
 120      * to the VM for code installation.
 121      */
 122     protected abstract CompiledCode createCompiledCode(ResolvedJavaMethod method, CompilationRequest compilationRequest, CompilationResult compilationResult, boolean isDefault, OptionValues options);
 123 
 124     /**
 125      * @see #createInstalledCode(DebugContext, ResolvedJavaMethod, CompilationRequest,
 126      *      CompilationResult, InstalledCode, boolean, Object[])
 127      */
 128     public InstalledCode createInstalledCode(DebugContext debug,
 129                     ResolvedJavaMethod method,
 130                     CompilationResult compilationResult,
 131                     InstalledCode predefinedInstalledCode,
 132                     boolean isDefault) {
 133         return createInstalledCode(debug, method, null, compilationResult, predefinedInstalledCode, isDefault, null);
 134     }
 135 
 136     /**
 137      * @see #createInstalledCode(DebugContext, ResolvedJavaMethod, CompilationRequest,
 138      *      CompilationResult, InstalledCode, boolean, Object[])
 139      */
 140     @SuppressWarnings("try")
 141     public InstalledCode createInstalledCode(DebugContext debug,
 142                     ResolvedJavaMethod method,
 143                     CompilationRequest compilationRequest,
 144                     CompilationResult compilationResult,
 145                     InstalledCode predefinedInstalledCode,
 146                     boolean isDefault) {
 147         return createInstalledCode(debug, method, compilationRequest, compilationResult, predefinedInstalledCode, isDefault, null);
 148     }
 149 
 150     /**
 151      * Installs code based on a given compilation result.
 152      *
 153      * @param method the method compiled to produce {@code compiledCode} or {@code null} if the
 154      *            input to {@code compResult} was not a {@link ResolvedJavaMethod}
 155      * @param compilationRequest the compilation request or {@code null}
 156      * @param compilationResult the code to be installed
 157      * @param predefinedInstalledCode a pre-allocated {@link InstalledCode} object to use as a
 158      *            reference to the installed code. If {@code null}, a new {@link InstalledCode}
 159      *            object will be created.
 160      * @param isDefault specifies if the installed code should be made the default implementation of
 161      *            {@code compRequest.getMethod()}. The default implementation for a method is the
 162      *            code executed for standard calls to the method. This argument is ignored if
 163      *            {@code compRequest == null}.
 164      * @param context a custom debug context to use for the code installation
 165      * @return a reference to the compiled and ready-to-run installed code
 166      * @throws BailoutException if the code installation failed
 167      * @throws IllegalArgumentException if {@code installedCode != null} and this platform does not
 168      *             {@linkplain CodeCacheProvider#installCode support} a predefined
 169      *             {@link InstalledCode} object
 170      */
 171     @SuppressWarnings("try")
 172     public InstalledCode createInstalledCode(DebugContext debug,
 173                     ResolvedJavaMethod method,
 174                     CompilationRequest compilationRequest,
 175                     CompilationResult compilationResult,
 176                     InstalledCode predefinedInstalledCode,
 177                     boolean isDefault,
 178                     Object[] context) {
 179         Object[] debugContext = context != null ? context : new Object[]{getProviders().getCodeCache(), method, compilationResult};
 180         CodeInstallationTask[] tasks;
 181         synchronized (this) {
 182             tasks = new CodeInstallationTask[codeInstallationTaskFactories.size()];
 183             for (int i = 0; i < codeInstallationTaskFactories.size(); i++) {
 184                 tasks[i] = codeInstallationTaskFactories.get(i).create();
 185             }
 186         }
 187         try (DebugContext.Scope s2 = debug.scope("CodeInstall", debugContext);
 188                         DebugContext.Activation a = debug.activate()) {
 189 
 190             InstalledCode installedCode;
 191             try {
 192                 preCodeInstallationTasks(tasks, compilationResult);
 193                 CompiledCode compiledCode = createCompiledCode(method, compilationRequest, compilationResult, isDefault, debug.getOptions());
 194                 installedCode = getProviders().getCodeCache().installCode(method, compiledCode, predefinedInstalledCode, compilationResult.getSpeculationLog(), isDefault);
 195                 assert predefinedInstalledCode == null || installedCode == predefinedInstalledCode;
 196             } catch (Throwable t) {
 197                 failCodeInstallationTasks(tasks, t);
 198                 throw t;
 199             }
 200 
 201             postCodeInstallationTasks(tasks, compilationResult, installedCode);
 202 
 203             return installedCode;
 204         } catch (Throwable e) {
 205             throw debug.handle(e);
 206         }
 207     }
 208 
 209     private static void failCodeInstallationTasks(CodeInstallationTask[] tasks, Throwable t) {
 210         for (CodeInstallationTask task : tasks) {
 211             task.installFailed(t);
 212         }
 213     }
 214 
 215     private static void preCodeInstallationTasks(CodeInstallationTask[] tasks, CompilationResult compilationResult) {
 216         for (CodeInstallationTask task : tasks) {
 217             task.preProcess(compilationResult);
 218         }
 219     }
 220 
 221     private static void postCodeInstallationTasks(CodeInstallationTask[] tasks, CompilationResult compilationResult, InstalledCode installedCode) {
 222         try {
 223             for (CodeInstallationTask task : tasks) {
 224                 task.postProcess(compilationResult, installedCode);
 225             }
 226         } catch (Throwable t) {
 227             installedCode.invalidate();
 228             throw t;
 229         }
 230     }
 231 
 232     /**
 233      * Installs code based on a given compilation result.
 234      *
 235      * @param method the method compiled to produce {@code compiledCode} or {@code null} if the
 236      *            input to {@code compResult} was not a {@link ResolvedJavaMethod}
 237      * @param compilationRequest the request or {@code null}
 238      * @param compilationResult the compiled code
 239      * @return a reference to the compiled and ready-to-run installed code
 240      * @throws BailoutException if the code installation failed
 241      */
 242     public InstalledCode addInstalledCode(DebugContext debug,
 243                     ResolvedJavaMethod method,
 244                     CompilationRequest compilationRequest,
 245                     CompilationResult compilationResult) {
 246         return createInstalledCode(debug, method, compilationRequest, compilationResult, null, false);
 247     }
 248 
 249     /**
 250      * Installs code based on a given compilation result and sets it as the default code to be used
 251      * when {@code method} is invoked.
 252      *
 253      * @param method the method compiled to produce {@code compiledCode} or {@code null} if the
 254      *            input to {@code compResult} was not a {@link ResolvedJavaMethod}
 255      * @param compilationResult the compiled code
 256      * @return a reference to the compiled and ready-to-run installed code
 257      * @throws BailoutException if the code installation failed
 258      */
 259     public InstalledCode createDefaultInstalledCode(DebugContext debug, ResolvedJavaMethod method, CompilationResult compilationResult) {
 260         System.out.println(compilationResult.getSpeculationLog());
 261         return createInstalledCode(debug, method, compilationResult, null, true);
 262     }
 263 
 264     /**
 265      * Gets the compilation id for a given {@link ResolvedJavaMethod}. Returns
 266      * {@code CompilationIdentifier#INVALID_COMPILATION_ID} in case there is no such id.
 267      *
 268      * @param resolvedJavaMethod
 269      */
 270     public CompilationIdentifier getCompilationIdentifier(ResolvedJavaMethod resolvedJavaMethod) {
 271         return CompilationIdentifier.INVALID_COMPILATION_ID;
 272     }
 273 
 274     public void emitBackEnd(StructuredGraph graph,
 275                     Object stub,
 276                     ResolvedJavaMethod installedCodeOwner,
 277                     CompilationResult compilationResult,
 278                     CompilationResultBuilderFactory factory,
 279                     RegisterConfig config, LIRSuites lirSuites) {
 280         LIRCompilerBackend.emitBackEnd(graph, stub, installedCodeOwner, this, compilationResult, factory, config, lirSuites);
 281     }
 282 
 283     /**
 284      * Encapsulates custom tasks done before and after code installation.
 285      */
 286     public abstract static class CodeInstallationTask {
 287         /**
 288          * Task to run before code installation.
 289          *
 290          * @param compilationResult the code about to be installed
 291          *
 292          */
 293         public void preProcess(CompilationResult compilationResult) {
 294         }
 295 
 296         /**
 297          * Task to run after the code is installed.
 298          *
 299          * @param compilationResult the code about to be installed
 300          * @param installedCode a reference to the installed code
 301          */
 302         public void postProcess(CompilationResult compilationResult, InstalledCode installedCode) {
 303         }
 304 
 305         /**
 306          * Invoked after {@link #preProcess} when code installation fails.
 307          *
 308          * @param cause the cause of the installation failure
 309          */
 310         public void installFailed(Throwable cause) {
 311         }
 312     }
 313 
 314     /**
 315      * Creates code installation tasks.
 316      */
 317     public abstract static class CodeInstallationTaskFactory {
 318         public abstract CodeInstallationTask create();
 319     }
 320 }