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;
  24 
  25 import java.util.Collection;
  26 import java.util.List;
  27 
  28 import org.graalvm.compiler.code.CompilationResult;
  29 import org.graalvm.compiler.core.LIRGenerationPhase.LIRGenerationContext;
  30 import org.graalvm.compiler.core.common.GraalOptions;
  31 import org.graalvm.compiler.core.common.alloc.ComputeBlockOrder;
  32 import org.graalvm.compiler.core.common.alloc.RegisterAllocationConfig;
  33 import org.graalvm.compiler.core.common.cfg.AbstractBlockBase;
  34 import org.graalvm.compiler.core.common.util.CompilationAlarm;
  35 import org.graalvm.compiler.core.target.Backend;
  36 import org.graalvm.compiler.debug.CounterKey;
  37 import org.graalvm.compiler.debug.DebugCloseable;
  38 import org.graalvm.compiler.debug.DebugContext;
  39 import org.graalvm.compiler.debug.GraalError;
  40 import org.graalvm.compiler.debug.MethodFilter;
  41 import org.graalvm.compiler.debug.TimerKey;
  42 import org.graalvm.compiler.lir.LIR;
  43 import org.graalvm.compiler.lir.alloc.OutOfRegistersException;
  44 import org.graalvm.compiler.lir.asm.CompilationResultBuilder;
  45 import org.graalvm.compiler.lir.asm.CompilationResultBuilderFactory;
  46 import org.graalvm.compiler.lir.framemap.FrameMap;
  47 import org.graalvm.compiler.lir.framemap.FrameMapBuilder;
  48 import org.graalvm.compiler.lir.gen.LIRGenerationResult;
  49 import org.graalvm.compiler.lir.gen.LIRGeneratorTool;
  50 import org.graalvm.compiler.lir.phases.AllocationPhase.AllocationContext;
  51 import org.graalvm.compiler.lir.phases.LIRSuites;
  52 import org.graalvm.compiler.lir.phases.PostAllocationOptimizationPhase.PostAllocationOptimizationContext;
  53 import org.graalvm.compiler.lir.phases.PreAllocationOptimizationPhase.PreAllocationOptimizationContext;
  54 import org.graalvm.compiler.nodes.StructuredGraph;
  55 import org.graalvm.compiler.nodes.StructuredGraph.ScheduleResult;
  56 import org.graalvm.compiler.nodes.cfg.Block;
  57 import org.graalvm.compiler.nodes.spi.NodeLIRBuilderTool;
  58 import org.graalvm.compiler.phases.OptimisticOptimizations;
  59 import org.graalvm.compiler.phases.PhaseSuite;
  60 import org.graalvm.compiler.phases.common.DeadCodeEliminationPhase;
  61 import org.graalvm.compiler.phases.tiers.HighTierContext;
  62 import org.graalvm.compiler.phases.tiers.LowTierContext;
  63 import org.graalvm.compiler.phases.tiers.MidTierContext;
  64 import org.graalvm.compiler.phases.tiers.Suites;
  65 import org.graalvm.compiler.phases.tiers.TargetProvider;
  66 import org.graalvm.compiler.phases.util.Providers;
  67 import org.graalvm.util.EconomicSet;
  68 
  69 import jdk.vm.ci.code.RegisterConfig;
  70 import jdk.vm.ci.code.TargetDescription;
  71 import jdk.vm.ci.code.site.ConstantReference;
  72 import jdk.vm.ci.code.site.DataPatch;
  73 import jdk.vm.ci.meta.Assumptions;
  74 import jdk.vm.ci.meta.JavaConstant;
  75 import jdk.vm.ci.meta.JavaKind;
  76 import jdk.vm.ci.meta.ProfilingInfo;
  77 import jdk.vm.ci.meta.ResolvedJavaField;
  78 import jdk.vm.ci.meta.ResolvedJavaMethod;
  79 import jdk.vm.ci.meta.VMConstant;
  80 
  81 /**
  82  * Static methods for orchestrating the compilation of a {@linkplain StructuredGraph graph}.
  83  */
  84 public class GraalCompiler {
  85 
  86     private static final TimerKey CompilerTimer = DebugContext.timer("GraalCompiler").doc("Time spent in compilation (excludes code installation).");
  87     private static final TimerKey FrontEnd = DebugContext.timer("FrontEnd").doc("Time spent processing HIR.");
  88     private static final TimerKey EmitLIR = DebugContext.timer("EmitLIR").doc("Time spent generating LIR from HIR.");
  89     private static final TimerKey EmitCode = DebugContext.timer("EmitCode").doc("Time spent generating machine code from LIR.");
  90     private static final TimerKey BackEnd = DebugContext.timer("BackEnd").doc("Time spent in EmitLIR and EmitCode.");
  91 
  92     /**
  93      * Encapsulates all the inputs to a {@linkplain GraalCompiler#compile(Request) compilation}.
  94      */
  95     public static class Request<T extends CompilationResult> {
  96         public final StructuredGraph graph;
  97         public final ResolvedJavaMethod installedCodeOwner;
  98         public final Providers providers;
  99         public final Backend backend;
 100         public final PhaseSuite<HighTierContext> graphBuilderSuite;
 101         public final OptimisticOptimizations optimisticOpts;
 102         public final ProfilingInfo profilingInfo;
 103         public final Suites suites;
 104         public final LIRSuites lirSuites;
 105         public final T compilationResult;
 106         public final CompilationResultBuilderFactory factory;
 107 
 108         /**
 109          * @param graph the graph to be compiled
 110          * @param installedCodeOwner the method the compiled code will be associated with once
 111          *            installed. This argument can be null.
 112          * @param providers
 113          * @param backend
 114          * @param graphBuilderSuite
 115          * @param optimisticOpts
 116          * @param profilingInfo
 117          * @param suites
 118          * @param lirSuites
 119          * @param compilationResult
 120          * @param factory
 121          */
 122         public Request(StructuredGraph graph, ResolvedJavaMethod installedCodeOwner, Providers providers, Backend backend, PhaseSuite<HighTierContext> graphBuilderSuite,
 123                         OptimisticOptimizations optimisticOpts, ProfilingInfo profilingInfo, Suites suites, LIRSuites lirSuites, T compilationResult, CompilationResultBuilderFactory factory) {
 124             this.graph = graph;
 125             this.installedCodeOwner = installedCodeOwner;
 126             this.providers = providers;
 127             this.backend = backend;
 128             this.graphBuilderSuite = graphBuilderSuite;
 129             this.optimisticOpts = optimisticOpts;
 130             this.profilingInfo = profilingInfo;
 131             this.suites = suites;
 132             this.lirSuites = lirSuites;
 133             this.compilationResult = compilationResult;
 134             this.factory = factory;
 135         }
 136 
 137         /**
 138          * Executes this compilation request.
 139          *
 140          * @return the result of the compilation
 141          */
 142         public T execute() {
 143             return GraalCompiler.compile(this);
 144         }
 145     }
 146 
 147     /**
 148      * Requests compilation of a given graph.
 149      *
 150      * @param graph the graph to be compiled
 151      * @param installedCodeOwner the method the compiled code will be associated with once
 152      *            installed. This argument can be null.
 153      * @return the result of the compilation
 154      */
 155     public static <T extends CompilationResult> T compileGraph(StructuredGraph graph, ResolvedJavaMethod installedCodeOwner, Providers providers, Backend backend,
 156                     PhaseSuite<HighTierContext> graphBuilderSuite, OptimisticOptimizations optimisticOpts, ProfilingInfo profilingInfo, Suites suites, LIRSuites lirSuites, T compilationResult,
 157                     CompilationResultBuilderFactory factory) {
 158         return compile(new Request<>(graph, installedCodeOwner, providers, backend, graphBuilderSuite, optimisticOpts, profilingInfo, suites, lirSuites, compilationResult, factory));
 159     }
 160 
 161     /**
 162      * Services a given compilation request.
 163      *
 164      * @return the result of the compilation
 165      */
 166     @SuppressWarnings("try")
 167     public static <T extends CompilationResult> T compile(Request<T> r) {
 168         DebugContext debug = r.graph.getDebug();
 169         try (CompilationAlarm alarm = CompilationAlarm.trackCompilationPeriod(r.graph.getOptions())) {
 170             assert !r.graph.isFrozen();
 171             try (DebugContext.Scope s0 = debug.scope("GraalCompiler", r.graph, r.providers.getCodeCache()); DebugCloseable a = CompilerTimer.start(debug)) {
 172                 emitFrontEnd(r.providers, r.backend, r.graph, r.graphBuilderSuite, r.optimisticOpts, r.profilingInfo, r.suites);
 173                 emitBackEnd(r.graph, null, r.installedCodeOwner, r.backend, r.compilationResult, r.factory, null, r.lirSuites);
 174             } catch (Throwable e) {
 175                 throw debug.handle(e);
 176             }
 177             checkForRequestedCrash(r.graph);
 178             return r.compilationResult;
 179         }
 180     }
 181 
 182     /**
 183      * Checks whether the {@link GraalCompilerOptions#CrashAt} option indicates that the compilation
 184      * of {@code graph} should result in an exception.
 185      *
 186      * @param graph a graph currently being compiled
 187      * @throws RuntimeException if the value of {@link GraalCompilerOptions#CrashAt} matches
 188      *             {@code graph.method()} or {@code graph.name}
 189      */
 190     private static void checkForRequestedCrash(StructuredGraph graph) {
 191         String methodPattern = GraalCompilerOptions.CrashAt.getValue(graph.getOptions());
 192         if (methodPattern != null) {
 193             String crashLabel = null;
 194             if (graph.name != null && graph.name.contains(methodPattern)) {
 195                 crashLabel = graph.name;
 196             }
 197             if (crashLabel == null) {
 198                 ResolvedJavaMethod method = graph.method();
 199                 MethodFilter[] filters = MethodFilter.parse(methodPattern);
 200                 for (MethodFilter filter : filters) {
 201                     if (filter.matches(method)) {
 202                         crashLabel = method.format("%H.%n(%p)");
 203                     }
 204                 }
 205             }
 206             if (crashLabel != null) {
 207                 throw new RuntimeException("Forced crash after compiling " + crashLabel);
 208             }
 209         }
 210     }
 211 
 212     /**
 213      * Builds the graph, optimizes it.
 214      */
 215     @SuppressWarnings("try")
 216     public static void emitFrontEnd(Providers providers, TargetProvider target, StructuredGraph graph, PhaseSuite<HighTierContext> graphBuilderSuite, OptimisticOptimizations optimisticOpts,
 217                     ProfilingInfo profilingInfo, Suites suites) {
 218         DebugContext debug = graph.getDebug();
 219         try (DebugContext.Scope s = debug.scope("FrontEnd"); DebugCloseable a = FrontEnd.start(debug)) {
 220             HighTierContext highTierContext = new HighTierContext(providers, graphBuilderSuite, optimisticOpts);
 221             if (graph.start().next() == null) {
 222                 graphBuilderSuite.apply(graph, highTierContext);
 223                 new DeadCodeEliminationPhase(DeadCodeEliminationPhase.Optionality.Optional).apply(graph);
 224                 debug.dump(DebugContext.BASIC_LEVEL, graph, "After parsing");
 225             } else {
 226                 debug.dump(DebugContext.INFO_LEVEL, graph, "initial state");
 227             }
 228 
 229             suites.getHighTier().apply(graph, highTierContext);
 230             graph.maybeCompress();
 231             debug.dump(DebugContext.BASIC_LEVEL, graph, "After high tier");
 232 
 233             MidTierContext midTierContext = new MidTierContext(providers, target, optimisticOpts, profilingInfo);
 234             suites.getMidTier().apply(graph, midTierContext);
 235             graph.maybeCompress();
 236             debug.dump(DebugContext.BASIC_LEVEL, graph, "After mid tier");
 237 
 238             LowTierContext lowTierContext = new LowTierContext(providers, target);
 239             suites.getLowTier().apply(graph, lowTierContext);
 240             debug.dump(DebugContext.BASIC_LEVEL, graph, "After low tier");
 241 
 242             debug.dump(DebugContext.BASIC_LEVEL, graph.getLastSchedule(), "Final HIR schedule");
 243         } catch (Throwable e) {
 244             throw debug.handle(e);
 245         } finally {
 246             graph.checkCancellation();
 247         }
 248     }
 249 
 250     @SuppressWarnings("try")
 251     public static <T extends CompilationResult> void emitBackEnd(StructuredGraph graph, Object stub, ResolvedJavaMethod installedCodeOwner, Backend backend, T compilationResult,
 252                     CompilationResultBuilderFactory factory, RegisterConfig registerConfig, LIRSuites lirSuites) {
 253         DebugContext debug = graph.getDebug();
 254         try (DebugContext.Scope s = debug.scope("BackEnd", graph.getLastSchedule()); DebugCloseable a = BackEnd.start(debug)) {
 255             LIRGenerationResult lirGen = null;
 256             lirGen = emitLIR(backend, graph, stub, registerConfig, lirSuites);
 257             try (DebugContext.Scope s2 = debug.scope("CodeGen", lirGen, lirGen.getLIR())) {
 258                 int bytecodeSize = graph.method() == null ? 0 : graph.getBytecodeSize();
 259                 compilationResult.setHasUnsafeAccess(graph.hasUnsafeAccess());
 260                 emitCode(backend, graph.getAssumptions(), graph.method(), graph.getMethods(), graph.getFields(), bytecodeSize, lirGen, compilationResult, installedCodeOwner, factory);
 261             } catch (Throwable e) {
 262                 throw debug.handle(e);
 263             }
 264         } catch (Throwable e) {
 265             throw debug.handle(e);
 266         } finally {
 267             graph.checkCancellation();
 268         }
 269     }
 270 
 271     @SuppressWarnings("try")
 272     public static LIRGenerationResult emitLIR(Backend backend, StructuredGraph graph, Object stub, RegisterConfig registerConfig, LIRSuites lirSuites) {
 273         String registerPressure = GraalOptions.RegisterPressure.getValue(graph.getOptions());
 274         String[] allocationRestrictedTo = registerPressure == null ? null : registerPressure.split(",");
 275         try {
 276             return emitLIR0(backend, graph, stub, registerConfig, lirSuites, allocationRestrictedTo);
 277         } catch (OutOfRegistersException e) {
 278             if (allocationRestrictedTo != null) {
 279                 allocationRestrictedTo = null;
 280                 return emitLIR0(backend, graph, stub, registerConfig, lirSuites, allocationRestrictedTo);
 281             }
 282             /* If the re-execution fails we convert the exception into a "hard" failure */
 283             throw new GraalError(e);
 284         } finally {
 285             graph.checkCancellation();
 286         }
 287     }
 288 
 289     @SuppressWarnings("try")
 290     private static LIRGenerationResult emitLIR0(Backend backend, StructuredGraph graph, Object stub, RegisterConfig registerConfig, LIRSuites lirSuites,
 291                     String[] allocationRestrictedTo) {
 292         DebugContext debug = graph.getDebug();
 293         try (DebugContext.Scope ds = debug.scope("EmitLIR"); DebugCloseable a = EmitLIR.start(debug)) {
 294             assert !graph.hasValueProxies();
 295             ScheduleResult schedule = graph.getLastSchedule();
 296             Block[] blocks = schedule.getCFG().getBlocks();
 297             Block startBlock = schedule.getCFG().getStartBlock();
 298             assert startBlock != null;
 299             assert startBlock.getPredecessorCount() == 0;
 300 
 301             AbstractBlockBase<?>[] codeEmittingOrder = ComputeBlockOrder.computeCodeEmittingOrder(blocks.length, startBlock);
 302             AbstractBlockBase<?>[] linearScanOrder = ComputeBlockOrder.computeLinearScanOrder(blocks.length, startBlock);
 303             LIR lir = new LIR(schedule.getCFG(), linearScanOrder, codeEmittingOrder, graph.getOptions(), graph.getDebug());
 304 
 305             FrameMapBuilder frameMapBuilder = backend.newFrameMapBuilder(registerConfig);
 306             LIRGenerationResult lirGenRes = backend.newLIRGenerationResult(graph.compilationId(), lir, frameMapBuilder, graph, stub);
 307             LIRGeneratorTool lirGen = backend.newLIRGenerator(lirGenRes);
 308             NodeLIRBuilderTool nodeLirGen = backend.newNodeLIRBuilder(graph, lirGen);
 309 
 310             // LIR generation
 311             LIRGenerationContext context = new LIRGenerationContext(lirGen, nodeLirGen, graph, schedule);
 312             new LIRGenerationPhase().apply(backend.getTarget(), lirGenRes, context);
 313 
 314             try (DebugContext.Scope s = debug.scope("LIRStages", nodeLirGen, lirGenRes, lir)) {
 315                 // Dump LIR along with HIR (the LIR is looked up from context)
 316                 debug.dump(DebugContext.BASIC_LEVEL, graph.getLastSchedule(), "After LIR generation");
 317                 LIRGenerationResult result = emitLowLevel(backend.getTarget(), lirGenRes, lirGen, lirSuites, backend.newRegisterAllocationConfig(registerConfig, allocationRestrictedTo));
 318                 return result;
 319             } catch (Throwable e) {
 320                 throw debug.handle(e);
 321             }
 322         } catch (Throwable e) {
 323             throw debug.handle(e);
 324         } finally {
 325             graph.checkCancellation();
 326         }
 327     }
 328 
 329     protected static <T extends CompilationResult> String getCompilationUnitName(StructuredGraph graph, T compilationResult) {
 330         if (compilationResult != null && compilationResult.getName() != null) {
 331             return compilationResult.getName();
 332         }
 333         ResolvedJavaMethod method = graph.method();
 334         if (method == null) {
 335             return "<unknown>";
 336         }
 337         return method.format("%H.%n(%p)");
 338     }
 339 
 340     public static LIRGenerationResult emitLowLevel(TargetDescription target, LIRGenerationResult lirGenRes, LIRGeneratorTool lirGen, LIRSuites lirSuites,
 341                     RegisterAllocationConfig registerAllocationConfig) {
 342         DebugContext debug = lirGenRes.getLIR().getDebug();
 343         PreAllocationOptimizationContext preAllocOptContext = new PreAllocationOptimizationContext(lirGen);
 344         lirSuites.getPreAllocationOptimizationStage().apply(target, lirGenRes, preAllocOptContext);
 345         debug.dump(DebugContext.BASIC_LEVEL, lirGenRes.getLIR(), "After PreAllocationOptimizationStage");
 346 
 347         AllocationContext allocContext = new AllocationContext(lirGen.getSpillMoveFactory(), registerAllocationConfig);
 348         lirSuites.getAllocationStage().apply(target, lirGenRes, allocContext);
 349         debug.dump(DebugContext.BASIC_LEVEL, lirGenRes.getLIR(), "After AllocationStage");
 350 
 351         PostAllocationOptimizationContext postAllocOptContext = new PostAllocationOptimizationContext(lirGen);
 352         lirSuites.getPostAllocationOptimizationStage().apply(target, lirGenRes, postAllocOptContext);
 353         debug.dump(DebugContext.BASIC_LEVEL, lirGenRes.getLIR(), "After PostAllocationOptimizationStage");
 354 
 355         return lirGenRes;
 356     }
 357 
 358     @SuppressWarnings("try")
 359     public static void emitCode(Backend backend, Assumptions assumptions, ResolvedJavaMethod rootMethod, Collection<ResolvedJavaMethod> inlinedMethods, EconomicSet<ResolvedJavaField> accessedFields,
 360                     int bytecodeSize, LIRGenerationResult lirGenRes,
 361                     CompilationResult compilationResult, ResolvedJavaMethod installedCodeOwner, CompilationResultBuilderFactory factory) {
 362         DebugContext debug = lirGenRes.getLIR().getDebug();
 363         try (DebugCloseable a = EmitCode.start(debug)) {
 364             FrameMap frameMap = lirGenRes.getFrameMap();
 365             CompilationResultBuilder crb = backend.newCompilationResultBuilder(lirGenRes, frameMap, compilationResult, factory);
 366             backend.emitCode(crb, lirGenRes.getLIR(), installedCodeOwner);
 367             if (assumptions != null && !assumptions.isEmpty()) {
 368                 compilationResult.setAssumptions(assumptions.toArray());
 369             }
 370             if (rootMethod != null) {
 371                 compilationResult.setMethods(rootMethod, inlinedMethods);
 372                 compilationResult.setFields(accessedFields);
 373                 compilationResult.setBytecodeSize(bytecodeSize);
 374             }
 375             crb.finish();
 376             if (debug.isCountEnabled()) {
 377                 List<DataPatch> ldp = compilationResult.getDataPatches();
 378                 JavaKind[] kindValues = JavaKind.values();
 379                 CounterKey[] dms = new CounterKey[kindValues.length];
 380                 for (int i = 0; i < dms.length; i++) {
 381                     dms[i] = DebugContext.counter("DataPatches-%s", kindValues[i]);
 382                 }
 383 
 384                 for (DataPatch dp : ldp) {
 385                     JavaKind kind = JavaKind.Illegal;
 386                     if (dp.reference instanceof ConstantReference) {
 387                         VMConstant constant = ((ConstantReference) dp.reference).getConstant();
 388                         if (constant instanceof JavaConstant) {
 389                             kind = ((JavaConstant) constant).getJavaKind();
 390                         }
 391                     }
 392                     dms[kind.ordinal()].add(debug, 1);
 393                 }
 394 
 395                 DebugContext.counter("CompilationResults").increment(debug);
 396                 DebugContext.counter("CodeBytesEmitted").add(debug, compilationResult.getTargetCodeSize());
 397                 DebugContext.counter("InfopointsEmitted").add(debug, compilationResult.getInfopoints().size());
 398                 DebugContext.counter("DataPatches").add(debug, ldp.size());
 399                 DebugContext.counter("ExceptionHandlersEmitted").add(debug, compilationResult.getExceptionHandlers().size());
 400             }
 401 
 402             debug.dump(DebugContext.BASIC_LEVEL, compilationResult, "After code generation");
 403         }
 404     }
 405 }