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