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