1/*
2 * Copyright (c) 2016, 2017, 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
24package jdk.tools.jaotc;
25
26import java.util.ListIterator;
27
28import org.graalvm.compiler.code.CompilationResult;
29import org.graalvm.compiler.core.GraalCompiler;
30import org.graalvm.compiler.core.common.CompilationIdentifier;
31import org.graalvm.compiler.core.common.CompilationIdentifier.Verbosity;
32import org.graalvm.compiler.debug.DebugContext;
33import org.graalvm.compiler.hotspot.HotSpotBackend;
34import org.graalvm.compiler.hotspot.HotSpotCompiledCodeBuilder;
35import org.graalvm.compiler.hotspot.meta.HotSpotProviders;
36import org.graalvm.compiler.java.GraphBuilderPhase;
37import org.graalvm.compiler.lir.asm.CompilationResultBuilderFactory;
38import org.graalvm.compiler.lir.phases.LIRSuites;
39import org.graalvm.compiler.nodes.StructuredGraph;
40import org.graalvm.compiler.nodes.graphbuilderconf.GraphBuilderConfiguration;
41import org.graalvm.compiler.nodes.graphbuilderconf.GraphBuilderConfiguration.Plugins;
42import org.graalvm.compiler.options.OptionValues;
43import org.graalvm.compiler.phases.BasePhase;
44import org.graalvm.compiler.phases.OptimisticOptimizations;
45import org.graalvm.compiler.phases.PhaseSuite;
46import org.graalvm.compiler.phases.tiers.HighTierContext;
47import org.graalvm.compiler.phases.tiers.Suites;
48
49import jdk.vm.ci.code.InstalledCode;
50import jdk.vm.ci.hotspot.HotSpotCodeCacheProvider;
51import jdk.vm.ci.hotspot.HotSpotResolvedJavaMethod;
52import jdk.vm.ci.meta.DefaultProfilingInfo;
53import jdk.vm.ci.meta.ProfilingInfo;
54import jdk.vm.ci.meta.ResolvedJavaMethod;
55import jdk.vm.ci.meta.TriState;
56
57final class AOTBackend {
58    private final Main main;
59    private final OptionValues graalOptions;
60    private final HotSpotBackend backend;
61    private final HotSpotProviders providers;
62    private final HotSpotCodeCacheProvider codeCache;
63    private final PhaseSuite<HighTierContext> graphBuilderSuite;
64    private final HighTierContext highTierContext;
65
66    AOTBackend(Main main, OptionValues graalOptions, HotSpotBackend backend) {
67        this.main = main;
68        this.graalOptions = graalOptions;
69        this.backend = backend;
70        providers = backend.getProviders();
71        codeCache = providers.getCodeCache();
72        graphBuilderSuite = initGraphBuilderSuite(backend, main.options.compileWithAssertions);
73        highTierContext = new HighTierContext(providers, graphBuilderSuite, OptimisticOptimizations.ALL);
74    }
75
76    PhaseSuite<HighTierContext> getGraphBuilderSuite() {
77        return graphBuilderSuite;
78    }
79
80    HotSpotBackend getBackend() {
81        return backend;
82    }
83
84    HotSpotProviders getProviders() {
85        return providers;
86    }
87
88    private Suites getSuites() {
89        // create suites every time, as we modify options for the compiler
90        return backend.getSuites().getDefaultSuites(graalOptions);
91    }
92
93    private LIRSuites getLirSuites() {
94        // create suites every time, as we modify options for the compiler
95        return backend.getSuites().getDefaultLIRSuites(graalOptions);
96    }
97
98    @SuppressWarnings("try")
99    CompilationResult compileMethod(ResolvedJavaMethod resolvedMethod, DebugContext debug) {
100        StructuredGraph graph = buildStructuredGraph(resolvedMethod, debug);
101        if (graph != null) {
102            return compileGraph(resolvedMethod, graph, debug);
103        }
104        return null;
105    }
106
107    /**
108     * Build a structured graph for the member.
109     *
110     * @param javaMethod method for whose code the graph is to be created
111     * @param debug
112     * @return structured graph
113     */
114    @SuppressWarnings("try")
115    private StructuredGraph buildStructuredGraph(ResolvedJavaMethod javaMethod, DebugContext debug) {
116        try (DebugContext.Scope s = debug.scope("AOTParseMethod")) {
117            StructuredGraph graph = new StructuredGraph.Builder(graalOptions, debug).method(javaMethod).useProfilingInfo(false).build();
118            graphBuilderSuite.apply(graph, highTierContext);
119            return graph;
120        } catch (Throwable e) {
121            main.handleError(javaMethod, e, " (building graph)");
122        }
123        return null;
124    }
125
126    @SuppressWarnings("try")
127    private CompilationResult compileGraph(ResolvedJavaMethod resolvedMethod, StructuredGraph graph, DebugContext debug) {
128        try (DebugContext.Scope s = debug.scope("AOTCompileMethod")) {
129            ProfilingInfo profilingInfo = DefaultProfilingInfo.get(TriState.FALSE);
130
131            final boolean isImmutablePIC = true;
132            CompilationIdentifier id = new CompilationIdentifier() {
133                @Override
134                public String toString(Verbosity verbosity) {
135                    return resolvedMethod.getName();
136                }
137            };
138            CompilationResult compilationResult = new CompilationResult(id, isImmutablePIC);
139
140            return GraalCompiler.compileGraph(graph, resolvedMethod, providers, backend, graphBuilderSuite, OptimisticOptimizations.ALL, profilingInfo, getSuites(), getLirSuites(),
141                            compilationResult, CompilationResultBuilderFactory.Default);
142
143        } catch (Throwable e) {
144            main.handleError(resolvedMethod, e, " (compiling graph)");
145        }
146        return null;
147    }
148
149    private static PhaseSuite<HighTierContext> initGraphBuilderSuite(HotSpotBackend backend, boolean compileWithAssertions) {
150        PhaseSuite<HighTierContext> graphBuilderSuite = backend.getSuites().getDefaultGraphBuilderSuite().copy();
151        ListIterator<BasePhase<? super HighTierContext>> iterator = graphBuilderSuite.findPhase(GraphBuilderPhase.class);
152        GraphBuilderConfiguration baseConfig = ((GraphBuilderPhase) iterator.previous()).getGraphBuilderConfig();
153
154        // Use all default plugins.
155        Plugins plugins = baseConfig.getPlugins();
156        GraphBuilderConfiguration aotConfig = GraphBuilderConfiguration.getDefault(plugins).withEagerResolving(true).withOmitAssertions(!compileWithAssertions);
157
158        iterator.next();
159        iterator.remove();
160        iterator.add(new GraphBuilderPhase(aotConfig));
161
162        return graphBuilderSuite;
163    }
164
165    void printCompiledMethod(HotSpotResolvedJavaMethod resolvedMethod, CompilationResult compResult) {
166        // This is really not installing the method.
167        InstalledCode installedCode = codeCache.addCode(resolvedMethod, HotSpotCompiledCodeBuilder.createCompiledCode(codeCache, null, null, compResult), null, null);
168        String disassembly = codeCache.disassemble(installedCode);
169        if (disassembly != null) {
170            main.printer.printlnDebug(disassembly);
171        }
172    }
173}
174