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