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