Path: blob/master/src/jdk.compiler/share/classes/com/sun/tools/sjavac/CompileJavaPackages.java
41175 views
/*1* Copyright (c) 2012, 2019, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package com.sun.tools.sjavac;2627import java.io.File;28import java.net.URI;29import java.util.ArrayList;30import java.util.Arrays;31import java.util.Collections;32import java.util.HashMap;33import java.util.List;34import java.util.Map;35import java.util.Random;36import java.util.Set;37import java.util.concurrent.Callable;38import java.util.concurrent.ExecutionException;39import java.util.concurrent.ExecutorService;40import java.util.concurrent.Executors;41import java.util.concurrent.Future;4243import com.sun.tools.javac.main.Main.Result;44import com.sun.tools.sjavac.comp.CompilationService;45import com.sun.tools.sjavac.options.Options;46import com.sun.tools.sjavac.pubapi.PubApi;47import com.sun.tools.sjavac.server.CompilationSubResult;48import com.sun.tools.sjavac.server.SysInfo;4950/**51* This transform compiles a set of packages containing Java sources.52* The compile request is divided into separate sets of source files.53* For each set a separate request thread is dispatched to a javac server54* and the meta data is accumulated. The number of sets correspond more or55* less to the number of cores. Less so now, than it will in the future.56*57* <p><b>This is NOT part of any supported API.58* If you write code that depends on this, you do so at your own59* risk. This code and its internal interfaces are subject to change60* or deletion without notice.</b></p>61*/62public class CompileJavaPackages implements Transformer {6364// The current limited sharing of data between concurrent JavaCompilers65// in the server will not give speedups above 3 cores. Thus this limit.66// We hope to improve this in the future.67static final int limitOnConcurrency = 3;6869Options args;7071public void setExtra(String e) {72}7374public void setExtra(Options a) {75args = a;76}7778public boolean transform(final CompilationService sjavac,79Map<String,Set<URI>> pkgSrcs,80final Set<URI> visibleSources,81Map<String,Set<String>> oldPackageDependents,82URI destRoot,83final Map<String,Set<URI>> packageArtifacts,84final Map<String,Map<String, Set<String>>> packageDependencies,85final Map<String,Map<String, Set<String>>> packageCpDependencies,86final Map<String, PubApi> packagePubapis,87final Map<String, PubApi> dependencyPubapis,88int debugLevel,89boolean incremental,90int numCores) {9192Log.debug("Performing CompileJavaPackages transform...");9394boolean rc = true;95boolean concurrentCompiles = true;9697// Fetch the id.98final String id = String.valueOf(new Random().nextInt());99// Only keep portfile and sjavac settings..100//String psServerSettings = Util.cleanSubOptions(Util.set("portfile","sjavac","background","keepalive"), sjavac.serverSettings());101102SysInfo sysinfo = sjavac.getSysInfo();103int numMBytes = (int)(sysinfo.maxMemory / ((long)(1024*1024)));104Log.debug("Server reports "+numMBytes+"MiB of memory and "+sysinfo.numCores+" cores");105106if (numCores <= 0) {107// Set the requested number of cores to the number of cores on the server.108numCores = sysinfo.numCores;109Log.debug("Number of jobs not explicitly set, defaulting to "+sysinfo.numCores);110} else if (sysinfo.numCores < numCores) {111// Set the requested number of cores to the number of cores on the server.112Log.debug("Limiting jobs from explicitly set "+numCores+" to cores available on server: "+sysinfo.numCores);113numCores = sysinfo.numCores;114} else {115Log.debug("Number of jobs explicitly set to "+numCores);116}117// More than three concurrent cores does not currently give a speedup, at least for compiling the jdk118// in the OpenJDK. This will change in the future.119int numCompiles = numCores;120if (numCores > limitOnConcurrency) numCompiles = limitOnConcurrency;121// Split the work up in chunks to compiled.122123int numSources = 0;124for (String s : pkgSrcs.keySet()) {125Set<URI> ss = pkgSrcs.get(s);126numSources += ss.size();127}128129int sourcesPerCompile = numSources / numCompiles;130131// For 64 bit Java, it seems we can compile the OpenJDK 8800 files with a 1500M of heap132// in a single chunk, with reasonable performance.133// For 32 bit java, it seems we need 1G of heap.134// Number experimentally determined when compiling the OpenJDK.135// Includes space for reasonably efficient garbage collection etc,136// Calculating backwards gives us a requirement of137// 1500M/8800 = 175 KiB for 64 bit platforms138// and 1G/8800 = 119 KiB for 32 bit platform139// for each compile.....140int kbPerFile = 175;141String osarch = System.getProperty("os.arch");142String dataModel = System.getProperty("sun.arch.data.model");143if ("32".equals(dataModel)) {144// For 32 bit platforms, assume it is slightly smaller145// because of smaller object headers and pointers.146kbPerFile = 119;147}148int numRequiredMBytes = (kbPerFile*numSources)/1024;149Log.debug("For os.arch "+osarch+" the empirically determined heap required per file is "+kbPerFile+"KiB");150Log.debug("Server has "+numMBytes+"MiB of heap.");151Log.debug("Heuristics say that we need "+numRequiredMBytes+"MiB of heap for all source files.");152// Perform heuristics to see how many cores we can use,153// or if we have to the work serially in smaller chunks.154if (numMBytes < numRequiredMBytes) {155// Ouch, cannot fit even a single compile into the heap.156// Split it up into several serial chunks.157concurrentCompiles = false;158// Limit the number of sources for each compile to 500.159if (numSources < 500) {160numCompiles = 1;161sourcesPerCompile = numSources;162Log.debug("Compiling as a single source code chunk to stay within heap size limitations!");163} else if (sourcesPerCompile > 500) {164// This number is very low, and tuned to dealing with the OpenJDK165// where the source is >very< circular! In normal application,166// with less circularity the number could perhaps be increased.167numCompiles = numSources / 500;168sourcesPerCompile = numSources/numCompiles;169Log.debug("Compiling source as "+numCompiles+" code chunks serially to stay within heap size limitations!");170}171} else {172if (numCompiles > 1) {173// Ok, we can fit at least one full compilation on the heap.174float usagePerCompile = (float)numRequiredMBytes / ((float)numCompiles * (float)0.7);175int usage = (int)(usagePerCompile * (float)numCompiles);176Log.debug("Heuristics say that for "+numCompiles+" concurrent compiles we need "+usage+"MiB");177if (usage > numMBytes) {178// Ouch it does not fit. Reduce to a single chunk.179numCompiles = 1;180sourcesPerCompile = numSources;181// What if the relationship between number of compile_chunks and num_required_mbytes182// is not linear? Then perhaps 2 chunks would fit where 3 does not. Well, this is183// something to experiment upon in the future.184Log.debug("Limiting compile to a single thread to stay within heap size limitations!");185}186}187}188189Log.debug("Compiling sources in "+numCompiles+" chunk(s)");190191// Create the chunks to be compiled.192final CompileChunk[] compileChunks = createCompileChunks(pkgSrcs, oldPackageDependents,193numCompiles, sourcesPerCompile);194195if (Log.isDebugging()) {196int cn = 1;197for (CompileChunk cc : compileChunks) {198Log.debug("Chunk "+cn+" for "+id+" ---------------");199cn++;200for (URI u : cc.srcs) {201Log.debug(""+u);202}203}204}205206long start = System.currentTimeMillis();207208// Prepare compilation calls209List<Callable<CompilationSubResult>> compilationCalls = new ArrayList<>();210final Object lock = new Object();211for (int i = 0; i < numCompiles; i++) {212CompileChunk cc = compileChunks[i];213if (cc.srcs.isEmpty()) {214continue;215}216217String chunkId = id + "-" + String.valueOf(i);218Log log = Log.get();219compilationCalls.add(() -> {220Log.setLogForCurrentThread(log);221CompilationSubResult result = sjavac.compile("n/a",222chunkId,223args.prepJavacArgs(),224Collections.emptyList(),225cc.srcs,226visibleSources);227synchronized (lock) {228Util.getLines(result.stdout).forEach(Log::info);229Util.getLines(result.stderr).forEach(Log::error);230}231return result;232});233}234235// Perform compilations and collect results236List<CompilationSubResult> subResults = new ArrayList<>();237List<Future<CompilationSubResult>> futs = new ArrayList<>();238ExecutorService exec = Executors.newFixedThreadPool(concurrentCompiles ? compilationCalls.size() : 1);239for (Callable<CompilationSubResult> compilationCall : compilationCalls) {240futs.add(exec.submit(compilationCall));241}242for (Future<CompilationSubResult> fut : futs) {243try {244subResults.add(fut.get());245} catch (ExecutionException ee) {246Log.error("Compilation failed: " + ee.getMessage());247Log.error(ee);248} catch (InterruptedException ie) {249Log.error("Compilation interrupted: " + ie.getMessage());250Log.error(ie);251Thread.currentThread().interrupt();252}253}254exec.shutdownNow();255256// Process each sub result257for (CompilationSubResult subResult : subResults) {258for (String pkg : subResult.packageArtifacts.keySet()) {259Set<URI> pkgArtifacts = subResult.packageArtifacts.get(pkg);260packageArtifacts.merge(pkg, pkgArtifacts, Util::union);261}262263for (String pkg : subResult.packageDependencies.keySet()) {264packageDependencies.putIfAbsent(pkg, new HashMap<>());265packageDependencies.get(pkg).putAll(subResult.packageDependencies.get(pkg));266}267268for (String pkg : subResult.packageCpDependencies.keySet()) {269packageCpDependencies.putIfAbsent(pkg, new HashMap<>());270packageCpDependencies.get(pkg).putAll(subResult.packageCpDependencies.get(pkg));271}272273for (String pkg : subResult.packagePubapis.keySet()) {274packagePubapis.merge(pkg, subResult.packagePubapis.get(pkg), PubApi::mergeTypes);275}276277for (String pkg : subResult.dependencyPubapis.keySet()) {278dependencyPubapis.merge(pkg, subResult.dependencyPubapis.get(pkg), PubApi::mergeTypes);279}280281// Check the return values.282if (subResult.result != Result.OK) {283rc = false;284}285}286287long duration = System.currentTimeMillis() - start;288long minutes = duration/60000;289long seconds = (duration-minutes*60000)/1000;290Log.debug("Compilation of "+numSources+" source files took "+minutes+"m "+seconds+"s");291292return rc;293}294295/**296* Split up the sources into compile chunks. If old package dependents information297* is available, sort the order of the chunks into the most dependent first!298* (Typically that chunk contains the java.lang package.) In the future299* we could perhaps improve the heuristics to put the sources into even more sensible chunks.300* Now the package are simple sorted in alphabetical order and chunked, then the chunks301* are sorted on how dependent they are.302*303* @param pkgSrcs The sources to compile.304* @param oldPackageDependents Old package dependents, if non-empty, used to sort the chunks.305* @param numCompiles The number of chunks.306* @param sourcesPerCompile The number of sources per chunk.307* @return308*/309CompileChunk[] createCompileChunks(Map<String,Set<URI>> pkgSrcs,310Map<String,Set<String>> oldPackageDependents,311int numCompiles,312int sourcesPerCompile) {313314CompileChunk[] compileChunks = new CompileChunk[numCompiles];315for (int i=0; i<compileChunks.length; ++i) {316compileChunks[i] = new CompileChunk();317}318319// Now go through the packages and spread out the source on the different chunks.320int ci = 0;321// Sort the packages322String[] packageNames = pkgSrcs.keySet().toArray(new String[0]);323Arrays.sort(packageNames);324String from = null;325for (String pkgName : packageNames) {326CompileChunk cc = compileChunks[ci];327Set<URI> s = pkgSrcs.get(pkgName);328if (cc.srcs.size()+s.size() > sourcesPerCompile && ci < numCompiles-1) {329from = null;330ci++;331cc = compileChunks[ci];332}333cc.numPackages++;334cc.srcs.addAll(s);335336// Calculate nice package names to use as information when compiling.337String justPkgName = Util.justPackageName(pkgName);338// Fetch how many packages depend on this package from the old build state.339Set<String> ss = oldPackageDependents.get(pkgName);340if (ss != null) {341// Accumulate this information onto this chunk.342cc.numDependents += ss.size();343}344if (from == null || from.trim().equals("")) from = justPkgName;345cc.pkgNames.append(justPkgName+"("+s.size()+") ");346cc.pkgFromTos = from+" to "+justPkgName;347}348// If we are compiling serially, sort the chunks, so that the chunk (with the most dependents) (usually the chunk349// containing java.lang.Object, is to be compiled first!350// For concurrent compilation, this does not matter.351Arrays.sort(compileChunks);352return compileChunks;353}354}355356357