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