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 package org.graalvm.compiler.hotspot.stubs;
  24 
  25 import static org.graalvm.compiler.core.GraalCompiler.emitBackEnd;
  26 import static org.graalvm.compiler.core.GraalCompiler.emitFrontEnd;
  27 import static org.graalvm.compiler.core.common.GraalOptions.GeneratePIC;
  28 import static org.graalvm.compiler.debug.GraalDebugConfig.Options.DebugStubsAndSnippets;
  29 import static org.graalvm.compiler.hotspot.HotSpotHostBackend.UNCOMMON_TRAP_HANDLER;
  30 import static org.graalvm.util.CollectionsUtil.allMatch;
  31 
  32 import java.util.ListIterator;
  33 
  34 import org.graalvm.compiler.code.CompilationResult;
  35 import org.graalvm.compiler.core.common.CompilationIdentifier;
  36 import org.graalvm.compiler.core.target.Backend;
  37 import org.graalvm.compiler.debug.Debug;
  38 import org.graalvm.compiler.debug.Debug.Scope;
  39 import org.graalvm.compiler.debug.DebugConfig;
  40 import org.graalvm.compiler.debug.internal.DebugScope;
  41 import org.graalvm.compiler.hotspot.HotSpotCompiledCodeBuilder;
  42 import org.graalvm.compiler.hotspot.HotSpotForeignCallLinkage;
  43 import org.graalvm.compiler.hotspot.meta.HotSpotProviders;
  44 import org.graalvm.compiler.hotspot.nodes.StubStartNode;
  45 import org.graalvm.compiler.lir.asm.CompilationResultBuilderFactory;
  46 import org.graalvm.compiler.lir.phases.LIRPhase;
  47 import org.graalvm.compiler.lir.phases.LIRSuites;
  48 import org.graalvm.compiler.lir.phases.PostAllocationOptimizationPhase.PostAllocationOptimizationContext;
  49 import org.graalvm.compiler.lir.profiling.MoveProfilingPhase;
  50 import org.graalvm.compiler.nodes.StructuredGraph;
  51 import org.graalvm.compiler.options.OptionValues;
  52 import org.graalvm.compiler.phases.OptimisticOptimizations;
  53 import org.graalvm.compiler.phases.PhaseSuite;
  54 import org.graalvm.compiler.phases.tiers.Suites;
  55 import org.graalvm.util.EconomicSet;
  56 
  57 import jdk.vm.ci.code.CodeCacheProvider;
  58 import jdk.vm.ci.code.InstalledCode;
  59 import jdk.vm.ci.code.Register;
  60 import jdk.vm.ci.code.RegisterConfig;
  61 import jdk.vm.ci.code.site.Call;
  62 import jdk.vm.ci.code.site.ConstantReference;
  63 import jdk.vm.ci.code.site.DataPatch;
  64 import jdk.vm.ci.code.site.Infopoint;
  65 import jdk.vm.ci.hotspot.HotSpotCompiledCode;
  66 import jdk.vm.ci.hotspot.HotSpotMetaspaceConstant;
  67 import jdk.vm.ci.meta.DefaultProfilingInfo;
  68 import jdk.vm.ci.meta.ResolvedJavaMethod;
  69 import jdk.vm.ci.meta.TriState;
  70 
  71 //JaCoCo Exclude
  72 
  73 /**
  74  * Base class for implementing some low level code providing the out-of-line slow path for a snippet
  75  * and/or a callee saved call to a HotSpot C/C++ runtime function or even a another compiled Java
  76  * method.
  77  */
  78 public abstract class Stub {
  79 
  80     /**
  81      * The linkage information for a call to this stub from compiled code.
  82      */
  83     protected final HotSpotForeignCallLinkage linkage;
  84 
  85     /**
  86      * The code installed for the stub.
  87      */
  88     protected InstalledCode code;
  89 
  90     /**
  91      * The registers destroyed by this stub (from the caller's perspective).
  92      */
  93     private EconomicSet<Register> destroyedCallerRegisters;
  94 
  95     private static boolean checkRegisterSetEquivalency(EconomicSet<Register> a, EconomicSet<Register> b) {
  96         if (a == b) {
  97             return true;
  98         }
  99         if (a.size() != b.size()) {
 100             return false;
 101         }
 102         return allMatch(a, e -> b.contains(e));
 103     }
 104 
 105     public void initDestroyedCallerRegisters(EconomicSet<Register> registers) {
 106         assert registers != null;
 107         assert destroyedCallerRegisters == null || checkRegisterSetEquivalency(registers, destroyedCallerRegisters) : "cannot redefine";
 108         destroyedCallerRegisters = registers;
 109     }
 110 
 111     /**
 112      * Gets the registers destroyed by this stub from a caller's perspective. These are the
 113      * temporaries of this stub and must thus be caller saved by a callers of this stub.
 114      */
 115     public EconomicSet<Register> getDestroyedCallerRegisters() {
 116         assert destroyedCallerRegisters != null : "not yet initialized";
 117         return destroyedCallerRegisters;
 118     }
 119 
 120     /**
 121      * Determines if this stub preserves all registers apart from those it
 122      * {@linkplain #getDestroyedCallerRegisters() destroys}.
 123      */
 124     public boolean preservesRegisters() {
 125         return true;
 126     }
 127 
 128     protected final OptionValues options;
 129     protected final HotSpotProviders providers;
 130 
 131     /**
 132      * Creates a new stub.
 133      *
 134      * @param linkage linkage details for a call to the stub
 135      */
 136     public Stub(OptionValues options, HotSpotProviders providers, HotSpotForeignCallLinkage linkage) {
 137         this.linkage = linkage;
 138         this.options = options;
 139         this.providers = providers;
 140     }
 141 
 142     /**
 143      * Gets the linkage for a call to this stub from compiled code.
 144      */
 145     public HotSpotForeignCallLinkage getLinkage() {
 146         return linkage;
 147     }
 148 
 149     public RegisterConfig getRegisterConfig() {
 150         return null;
 151     }
 152 
 153     /**
 154      * Gets the graph that from which the code for this stub will be compiled.
 155      *
 156      * @param compilationId unique compilation id for the stub
 157      */
 158     protected abstract StructuredGraph getGraph(CompilationIdentifier compilationId);
 159 
 160     @Override
 161     public String toString() {
 162         return "Stub<" + linkage.getDescriptor() + ">";
 163     }
 164 
 165     /**
 166      * Gets the method the stub's code will be associated with once installed. This may be null.
 167      */
 168     protected abstract ResolvedJavaMethod getInstalledCodeOwner();
 169 
 170     /**
 171      * Gets a context object for the debug scope created when producing the code for this stub.
 172      */
 173     protected abstract Object debugScopeContext();
 174 
 175     /**
 176      * Gets the code for this stub, compiling it first if necessary.
 177      */
 178     @SuppressWarnings("try")
 179     public synchronized InstalledCode getCode(final Backend backend) {
 180         if (code == null) {
 181             DebugConfig config = DebugStubsAndSnippets.getValue(options) ? DebugScope.getConfig() : Debug.silentConfig();
 182             try (Scope d = Debug.sandbox("CompilingStub", config, providers.getCodeCache(), debugScopeContext())) {
 183                 CodeCacheProvider codeCache = providers.getCodeCache();
 184 
 185                 CompilationResult compResult = buildCompilationResult(backend);
 186                 try (Scope s = Debug.scope("CodeInstall", compResult)) {
 187                     assert destroyedCallerRegisters != null;
 188                     // Add a GeneratePIC check here later, we don't want to install
 189                     // code if we don't have a corresponding VM global symbol.
 190                     HotSpotCompiledCode compiledCode = HotSpotCompiledCodeBuilder.createCompiledCode(codeCache, null, null, compResult);
 191                     code = codeCache.installCode(null, compiledCode, null, null, false);
 192                 } catch (Throwable e) {
 193                     throw Debug.handle(e);
 194                 }
 195             } catch (Throwable e) {
 196                 throw Debug.handle(e);
 197             }
 198             assert code != null : "error installing stub " + this;
 199         }
 200 
 201         return code;
 202     }
 203 
 204     @SuppressWarnings("try")
 205     private CompilationResult buildCompilationResult(final Backend backend) {
 206         CompilationResult compResult = new CompilationResult(toString(), GeneratePIC.getValue(options));
 207         final StructuredGraph graph = getGraph(getStubCompilationId());
 208 
 209         // Stubs cannot be recompiled so they cannot be compiled with assumptions
 210         assert graph.getAssumptions() == null;
 211 
 212         if (!(graph.start() instanceof StubStartNode)) {
 213             StubStartNode newStart = graph.add(new StubStartNode(Stub.this));
 214             newStart.setStateAfter(graph.start().stateAfter());
 215             graph.replaceFixed(graph.start(), newStart);
 216         }
 217 
 218         try (Scope s0 = Debug.scope("StubCompilation", graph, providers.getCodeCache())) {
 219             Suites suites = createSuites();
 220             emitFrontEnd(providers, backend, graph, providers.getSuites().getDefaultGraphBuilderSuite(), OptimisticOptimizations.ALL, DefaultProfilingInfo.get(TriState.UNKNOWN), suites);
 221             LIRSuites lirSuites = createLIRSuites();
 222             emitBackEnd(graph, Stub.this, getInstalledCodeOwner(), backend, compResult, CompilationResultBuilderFactory.Default, getRegisterConfig(), lirSuites);
 223             assert checkStubInvariants(compResult);
 224         } catch (Throwable e) {
 225             throw Debug.handle(e);
 226         }
 227         return compResult;
 228     }
 229 
 230     /**
 231      * Gets a {@link CompilationResult} that can be used for code generation. Required for AOT.
 232      */
 233     @SuppressWarnings("try")
 234     public CompilationResult getCompilationResult(final Backend backend) {
 235         try (Scope d = Debug.sandbox("CompilingStub", DebugScope.getConfig(), providers.getCodeCache(), debugScopeContext())) {
 236             return buildCompilationResult(backend);
 237         } catch (Throwable e) {
 238             throw Debug.handle(e);
 239         }
 240     }
 241 
 242     public CompilationIdentifier getStubCompilationId() {
 243         return new StubCompilationIdentifier(this);
 244     }
 245 
 246     /**
 247      * Checks the conditions a compilation must satisfy to be installed as a RuntimeStub.
 248      */
 249     private boolean checkStubInvariants(CompilationResult compResult) {
 250         assert compResult.getExceptionHandlers().isEmpty() : this;
 251 
 252         // Stubs cannot be recompiled so they cannot be compiled with
 253         // assumptions and there is no point in recording evol_method dependencies
 254         assert compResult.getAssumptions() == null : "stubs should not use assumptions: " + this;
 255 
 256         for (DataPatch data : compResult.getDataPatches()) {
 257             if (data.reference instanceof ConstantReference) {
 258                 ConstantReference ref = (ConstantReference) data.reference;
 259                 if (ref.getConstant() instanceof HotSpotMetaspaceConstant) {
 260                     HotSpotMetaspaceConstant c = (HotSpotMetaspaceConstant) ref.getConstant();
 261                     if (c.asResolvedJavaType() != null && c.asResolvedJavaType().getName().equals("[I")) {
 262                         // special handling for NewArrayStub
 263                         // embedding the type '[I' is safe, since it is never unloaded
 264                         continue;
 265                     }
 266                 }
 267             }
 268 
 269             assert !(data.reference instanceof ConstantReference) : this + " cannot have embedded object or metadata constant: " + data.reference;
 270         }
 271         for (Infopoint infopoint : compResult.getInfopoints()) {
 272             assert infopoint instanceof Call : this + " cannot have non-call infopoint: " + infopoint;
 273             Call call = (Call) infopoint;
 274             assert call.target instanceof HotSpotForeignCallLinkage : this + " cannot have non runtime call: " + call.target;
 275             HotSpotForeignCallLinkage callLinkage = (HotSpotForeignCallLinkage) call.target;
 276             assert !callLinkage.isCompiledStub() || callLinkage.getDescriptor().equals(UNCOMMON_TRAP_HANDLER) : this + " cannot call compiled stub " + callLinkage;
 277         }
 278         return true;
 279     }
 280 
 281     protected Suites createSuites() {
 282         Suites defaultSuites = providers.getSuites().getDefaultSuites(options);
 283         return new Suites(new PhaseSuite<>(), defaultSuites.getMidTier(), defaultSuites.getLowTier());
 284     }
 285 
 286     protected LIRSuites createLIRSuites() {
 287         LIRSuites lirSuites = new LIRSuites(providers.getSuites().getDefaultLIRSuites(options));
 288         ListIterator<LIRPhase<PostAllocationOptimizationContext>> moveProfiling = lirSuites.getPostAllocationOptimizationStage().findPhase(MoveProfilingPhase.class);
 289         if (moveProfiling != null) {
 290             moveProfiling.remove();
 291         }
 292         return lirSuites;
 293     }
 294 }