1/*
2 * Copyright (c) 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 */
23package org.graalvm.compiler.hotspot;
24
25import static jdk.vm.ci.common.InitTimer.timer;
26
27import java.util.ArrayList;
28import java.util.Collections;
29import java.util.List;
30import java.util.stream.Collectors;
31
32import org.graalvm.compiler.debug.Assertions;
33import org.graalvm.compiler.debug.GraalError;
34import org.graalvm.compiler.options.Option;
35import org.graalvm.compiler.options.OptionKey;
36import org.graalvm.compiler.options.OptionType;
37import org.graalvm.compiler.options.OptionValues;
38import org.graalvm.compiler.phases.tiers.CompilerConfiguration;
39import org.graalvm.compiler.serviceprovider.GraalServices;
40import org.graalvm.util.EconomicMap;
41
42import jdk.vm.ci.code.Architecture;
43import jdk.vm.ci.common.InitTimer;
44
45/**
46 * A factory that creates the {@link CompilerConfiguration} the Graal compiler will use. Each
47 * factory must have a unique {@link #name} and {@link #autoSelectionPriority}. The latter imposes a
48 * total ordering between factories for the purpose of auto-selecting the factory to use.
49 */
50public abstract class CompilerConfigurationFactory implements Comparable<CompilerConfigurationFactory> {
51
52    static class Options {
53        // @formatter:off
54        @Option(help = "Names the Graal compiler configuration to use. If ommitted, the compiler configuration " +
55                       "with the highest auto-selection priority is used. To see the set of available configurations, " +
56                       "supply the value 'help' to this option.", type = OptionType.Expert)
57        public static final OptionKey<String> CompilerConfiguration = new OptionKey<>(null);
58        // @formatter:on
59    }
60
61    /**
62     * The name of this factory. This must be unique across all factory instances and is used when
63     * selecting a factory based on the value of {@link Options#CompilerConfiguration}.
64     */
65    private final String name;
66
67    /**
68     * The priority of this factory. This must be unique across all factory instances and is used
69     * when selecting a factory when {@link Options#CompilerConfiguration} is omitted
70     */
71    private final int autoSelectionPriority;
72
73    protected CompilerConfigurationFactory(String name, int autoSelectionPriority) {
74        this.name = name;
75        this.autoSelectionPriority = autoSelectionPriority;
76        assert checkAndAddNewFactory(this);
77    }
78
79    public abstract CompilerConfiguration createCompilerConfiguration();
80
81    /**
82     * Collect the set of available {@linkplain HotSpotBackendFactory backends} for this compiler
83     * configuration.
84     */
85    public BackendMap createBackendMap() {
86        // default to backend with the same name as the compiler configuration
87        return new DefaultBackendMap(name);
88    }
89
90    public interface BackendMap {
91        HotSpotBackendFactory getBackendFactory(Architecture arch);
92    }
93
94    public static class DefaultBackendMap implements BackendMap {
95
96        private final EconomicMap<Class<? extends Architecture>, HotSpotBackendFactory> backends = EconomicMap.create();
97
98        @SuppressWarnings("try")
99        public DefaultBackendMap(String backendName) {
100            try (InitTimer t = timer("HotSpotBackendFactory.register")) {
101                for (HotSpotBackendFactory backend : GraalServices.load(HotSpotBackendFactory.class)) {
102                    if (backend.getName().equals(backendName)) {
103                        Class<? extends Architecture> arch = backend.getArchitecture();
104                        HotSpotBackendFactory oldEntry = backends.put(arch, backend);
105                        assert oldEntry == null || oldEntry == backend : "duplicate Graal backend";
106                    }
107                }
108            }
109        }
110
111        @Override
112        public final HotSpotBackendFactory getBackendFactory(Architecture arch) {
113            return backends.get(arch.getClass());
114        }
115    }
116
117    @Override
118    public int compareTo(CompilerConfigurationFactory o) {
119        if (autoSelectionPriority > o.autoSelectionPriority) {
120            return -1;
121        }
122        if (autoSelectionPriority < o.autoSelectionPriority) {
123            return 1;
124        }
125        assert this == o : "distinct compiler configurations cannot have the same auto selection priority";
126        return 0;
127    }
128
129    /**
130     * List used to assert uniqueness of {@link #name} and {@link #autoSelectionPriority} across all
131     * {@link CompilerConfigurationFactory} instances.
132     */
133    private static final List<CompilerConfigurationFactory> factories = Assertions.assertionsEnabled() ? new ArrayList<>() : null;
134
135    private static boolean checkAndAddNewFactory(CompilerConfigurationFactory factory) {
136        for (CompilerConfigurationFactory other : factories) {
137            assert !other.name.equals(factory.name) : factory.getClass().getName() + " cannot have the same selector as " + other.getClass().getName() + ": " + factory.name;
138            assert other.autoSelectionPriority != factory.autoSelectionPriority : factory.getClass().getName() + " cannot have the same auto-selection priority as " + other.getClass().getName() +
139                            ": " + factory.autoSelectionPriority;
140        }
141        factories.add(factory);
142        return true;
143    }
144
145    /**
146     * @return sorted list of {@link CompilerConfigurationFactory}s
147     */
148    private static List<CompilerConfigurationFactory> getAllCandidates() {
149        List<CompilerConfigurationFactory> candidates = new ArrayList<>();
150        for (CompilerConfigurationFactory candidate : GraalServices.load(CompilerConfigurationFactory.class)) {
151            candidates.add(candidate);
152        }
153        Collections.sort(candidates);
154        return candidates;
155    }
156
157    /**
158     * Selects and instantiates a {@link CompilerConfigurationFactory}. The selection algorithm is
159     * as follows: if {@code name} is non-null, then select the factory with the same name else if
160     * {@code Options.CompilerConfiguration.getValue()} is non-null then select the factory whose
161     * name matches the value else select the factory with the highest
162     * {@link #autoSelectionPriority} value.
163     *
164     * @param name the name of the compiler configuration to select (optional)
165     */
166    @SuppressWarnings("try")
167    public static CompilerConfigurationFactory selectFactory(String name, OptionValues options) {
168        CompilerConfigurationFactory factory = null;
169        try (InitTimer t = timer("CompilerConfigurationFactory.selectFactory")) {
170            String value = name == null ? Options.CompilerConfiguration.getValue(options) : name;
171            if ("help".equals(value)) {
172                System.out.println("The available Graal compiler configurations are:");
173                for (CompilerConfigurationFactory candidate : getAllCandidates()) {
174                    System.out.println("    " + candidate.name);
175                }
176                System.exit(0);
177            } else if (value != null) {
178                for (CompilerConfigurationFactory candidate : GraalServices.load(CompilerConfigurationFactory.class)) {
179                    if (candidate.name.equals(value)) {
180                        factory = candidate;
181                        break;
182                    }
183                }
184                if (factory == null) {
185                    throw new GraalError("Graal compiler configuration '%s' not found. Available configurations are: %s", value,
186                                    getAllCandidates().stream().map(c -> c.name).collect(Collectors.joining(", ")));
187                }
188            } else {
189                List<CompilerConfigurationFactory> candidates = getAllCandidates();
190                if (candidates.isEmpty()) {
191                    throw new GraalError("No %s providers found", CompilerConfigurationFactory.class.getName());
192                }
193                factory = candidates.get(0);
194            }
195        }
196        return factory;
197    }
198}
199