-
Notifications
You must be signed in to change notification settings - Fork 112
Make ktfmt up to 100x faster via native-image
#584
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
sgammon
wants to merge
4
commits into
facebook:main
Choose a base branch
from
sgammon:feat/native-image
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+2,751
−11
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| core/src/main/native-image/resources/META-INF/native-image/com/facebook/ktfmt/reachability-metadata.json linguist-generated=true |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
251 changes: 251 additions & 0 deletions
251
buildSrc/src/main/kotlin/com/facebook/ktfmt/NativeImagePlugin.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,251 @@ | ||
| /* | ||
| * Copyright (c) Meta Platforms, Inc. and affiliates. | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| package com.facebook.ktfmt | ||
|
|
||
| import org.graalvm.buildtools.gradle.dsl.GraalVMExtension | ||
| import org.gradle.api.GradleException | ||
| import org.gradle.api.Plugin | ||
| import org.gradle.api.Project | ||
| import org.gradle.api.artifacts.Configuration | ||
| import org.gradle.api.artifacts.VersionCatalogsExtension | ||
| import org.gradle.api.plugins.JavaApplication | ||
| import org.gradle.api.plugins.JavaPluginExtension | ||
| import org.gradle.jvm.tasks.Jar | ||
| import org.gradle.kotlin.dsl.configure | ||
| import org.gradle.kotlin.dsl.getByType | ||
| import org.gradle.kotlin.dsl.named | ||
| import org.gradle.kotlin.dsl.register | ||
|
|
||
| @Suppress("unused") | ||
| class NativeImagePlugin : Plugin<Project> { | ||
| override fun apply(project: Project) { | ||
| project.plugins.apply("application") | ||
| project.plugins.apply("org.graalvm.buildtools.native") | ||
|
|
||
| project.extensions.configure<JavaApplication> { mainClass.set(ENTRYPOINT) } | ||
|
|
||
| project.plugins.withId("java") { configureNativeImage(project) } | ||
| } | ||
|
|
||
| private fun configureNativeImage(project: Project) { | ||
| val nativeImageLibs = | ||
| project.extensions.getByType<VersionCatalogsExtension>().named("nativeImageLibs") | ||
|
|
||
| val nativeImageJavacClasspath: Configuration = | ||
| project.configurations.create("nativeImageJavacClasspath") { | ||
| extendsFrom(project.configurations.getByName("implementation")) | ||
| isCanBeResolved = true | ||
| } | ||
|
|
||
| project.dependencies.apply { | ||
| add("nativeImageJavacClasspath", nativeImageLibs.findLibrary("graalvm-nativeimage").get()) | ||
| add("nativeImageClasspath", nativeImageLibs.findLibrary("jline-terminal").get()) | ||
| add("nativeImageClasspath", nativeImageLibs.findLibrary("jline-terminal-jansi").get()) | ||
| add("nativeImageClasspath", nativeImageLibs.findLibrary("jline-terminal-jna").get()) | ||
| add("nativeImageClasspath", nativeImageLibs.findLibrary("jline-terminal-jni").get()) | ||
| } | ||
|
|
||
| val nativeImageDir = project.layout.projectDirectory.dir(NATIVE_IMAGE_SRC_DIR) | ||
| val javaExtension = project.extensions.getByType<JavaPluginExtension>() | ||
| val nativeImageSourceSet = | ||
| javaExtension.sourceSets.create("nativeImage") { | ||
| java.srcDir(nativeImageDir.dir("java")) | ||
| resources.srcDir(nativeImageDir.dir("resources")) | ||
| } | ||
|
|
||
| val compileNativeImageClasses = | ||
| project.tasks.register( | ||
| "compileNativeImageClasses", | ||
| org.gradle.api.tasks.compile.JavaCompile::class, | ||
| ) { | ||
| group = "build" | ||
| description = "Compiles Native Image helper classes" | ||
| source = nativeImageSourceSet.java | ||
| classpath = nativeImageJavacClasspath | ||
| destinationDirectory.set(project.layout.buildDirectory.dir("classes/native-image")) | ||
| dependsOn(project.tasks.named("compileJava")) | ||
| } | ||
|
|
||
| val nativeImageJar = | ||
| project.tasks.register("nativeImageJar", Jar::class) { | ||
| group = "build" | ||
| description = "Assembles Native Image jar and resources" | ||
| dependsOn(compileNativeImageClasses) | ||
| from(project.layout.buildDirectory.dir("classes/native-image")) | ||
| from(nativeImageSourceSet.resources) | ||
| archiveClassifier.set("nativeimage") | ||
| } | ||
|
|
||
| project.tasks.named("nativeCompile") { dependsOn(compileNativeImageClasses, nativeImageJar) } | ||
|
|
||
| configureGraalvmNative(project, nativeImageJar) | ||
| } | ||
|
|
||
| private fun configureGraalvmNative( | ||
| project: Project, | ||
| nativeImageJar: org.gradle.api.tasks.TaskProvider<Jar>, | ||
| ) { | ||
| val nativeRelease = project.findProperty("ktfmt.native.release") == "true" | ||
| val nativeTarget = project.findProperty("ktfmt.native.target") ?: "compatibility" | ||
| val nativeGc = project.findProperty("ktfmt.native.gc") ?: "serial" | ||
| val nativeDebug = project.findProperty("ktfmt.native.debug") == "true" | ||
| val enableLto = project.findProperty("ktfmt.native.lto") == "true" | ||
| val muslSysroot = | ||
| (project.findProperty("ktfmt.native.muslHome") ?: System.getenv("MUSL_HOME"))?.toString() | ||
| val preferMusl = | ||
| (project.findProperty("ktfmt.native.musl") == "true").also { enabled -> | ||
| require(!enabled || muslSysroot != null) { | ||
| "When `ktfmt.native.musl` is true, -Pktfmt.native.muslHome or MUSL_HOME must be set to the Musl sysroot. " + | ||
| "See https://www.graalvm.org/latest/reference-manual/native-image/guides/build-static-executables/" | ||
| } | ||
| } | ||
| val preferSmol = project.findProperty("ktfmt.native.smol") == "true" | ||
| val nativeOpt = | ||
| when (val opt = project.findProperty("ktfmt.native.opt")) { | ||
| null -> | ||
| when { | ||
| preferSmol -> "s" | ||
| nativeRelease -> "3" | ||
| else -> "b" | ||
| } | ||
| else -> opt | ||
| } | ||
|
|
||
| project.extensions.configure<GraalVMExtension>("graalvmNative") { | ||
| binaries.named("main") { | ||
| imageName.set("ktfmt") | ||
| mainClass.set(ENTRYPOINT) | ||
| classpath( | ||
| project.files( | ||
| nativeImageJar.flatMap { it.archiveFile }, | ||
| project.tasks.named("jar", Jar::class).flatMap { it.archiveFile }, | ||
| project.configurations.getByName("compileClasspath"), | ||
| project.configurations.getByName("runtimeClasspath"), | ||
| project.configurations.getByName("nativeImageClasspath"), | ||
| ) | ||
| ) | ||
| buildArgs( | ||
| buildNativeImageArgs( | ||
| project, | ||
| nativeOpt, | ||
| nativeTarget, | ||
| nativeDebug, | ||
| nativeGc, | ||
| enableLto, | ||
| preferMusl, | ||
| muslSysroot, | ||
| ) | ||
| ) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private fun buildNativeImageArgs( | ||
| project: Project, | ||
| nativeOpt: Any, | ||
| nativeTarget: Any, | ||
| nativeDebug: Boolean, | ||
| nativeGc: Any, | ||
| enableLto: Boolean, | ||
| preferMusl: Boolean, | ||
| muslSysroot: String?, | ||
| ): List<String> = buildList { | ||
| add("-O$nativeOpt") | ||
| add("-march=$nativeTarget") | ||
| if (nativeDebug) { | ||
| add("-g") | ||
| add("-H:+SourceLevelDebug") | ||
| } | ||
|
|
||
| add("--no-fallback") | ||
| add("--gc=$nativeGc") | ||
| add("--future-defaults=all") | ||
| add("--link-at-build-time=com.facebook") | ||
| add("--initialize-at-build-time=com.facebook") | ||
| add("--add-opens=java.base/java.util=ALL-UNNAMED") | ||
| add("--color=always") | ||
| add("-H:+ReportExceptionStackTraces") | ||
| add("-H:-UseContainerSupport") | ||
| add("-R:+InstallSegfaultHandler") | ||
| add("-H:+UnlockExperimentalVMOptions") | ||
| add("-H:-ReduceImplicitExceptionStackTraceInformation") | ||
| add("-H:-UnlockExperimentalVMOptions") | ||
| add("-J--enable-native-access=ALL-UNNAMED") | ||
| add("-J--illegal-native-access=allow") | ||
| add("-J--sun-misc-unsafe-memory-access=allow") | ||
|
|
||
| if (enableLto) { | ||
| add("--native-compiler-options=-flto") | ||
| add("-H:NativeLinkerOption=-flto") | ||
| } | ||
| if (preferMusl) { | ||
| add("-H:NativeLinkerOption=-L${muslSysroot}/lib") | ||
| } | ||
|
|
||
| addLinesFromFile(project, "initialize-at-build-time.txt") { "--initialize-at-build-time=$it" } | ||
| addLinesFromFile(project, "initialize-at-run-time.txt") { "--initialize-at-run-time=$it" } | ||
|
|
||
| when (System.getProperty("os.name")) { | ||
| "Linux" -> | ||
| when (normalizeArch(System.getProperty("os.arch"))) { | ||
| "x64" -> | ||
| if (preferMusl) { | ||
| addAll(listOf("--static", "--libc=musl", "-H:+StaticLibStdCpp")) | ||
| } else { | ||
| add("--static-nolibc") | ||
| } | ||
| else -> add("--static-nolibc") | ||
| } | ||
| "Mac OS X" -> add("--static-nolibc") | ||
| } | ||
| } | ||
|
|
||
| /** Canonicalizes [java.lang.System.getProperty]("os.arch") values that vary across JVMs. */ | ||
| private fun normalizeArch(arch: String?): String = | ||
| when (arch) { | ||
| "amd64", | ||
| "x86_64" -> "x64" | ||
| "aarch64", | ||
| "arm64" -> "aarch64" | ||
| else -> arch.orEmpty() | ||
| } | ||
|
|
||
| private fun MutableList<String>.addLinesFromFile( | ||
| project: Project, | ||
| fileName: String, | ||
| mapper: (String) -> String, | ||
| ) { | ||
| val file = project.layout.projectDirectory.dir(NATIVE_IMAGE_SRC_DIR).file(fileName).asFile | ||
| if (!file.exists()) { | ||
| throw GradleException("Native Image configuration file not found: $file") | ||
| } | ||
| file | ||
| .useLines { lines -> | ||
| lines | ||
| .map { it.trim() } | ||
| .filter { it.isNotEmpty() && !it.startsWith("#") } | ||
| .map(mapper) | ||
| .toList() | ||
| } | ||
| .also { addAll(it) } | ||
| } | ||
|
|
||
| private companion object { | ||
| const val ENTRYPOINT = "com.facebook.ktfmt.cli.Main" | ||
| const val NATIVE_IMAGE_SRC_DIR = "src/main/native-image" | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| com.google.common.collect.SingletonImmutableList | ||
| kotlin.Function | ||
| kotlin.KotlinVersion | ||
| kotlin.SynchronizedLazyImpl | ||
| kotlin.UNINITIALIZED_VALUE | ||
| kotlin.collections.AbstractList$Companion | ||
| kotlin.collections.EmptyMap | ||
| kotlin.enums.EnumEntriesList | ||
| kotlin.jvm.functions.Function1 | ||
| kotlin.text.Regex |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| # Some ktfmt classes build run-time-only object graphs in their <clinit> (ec4j config types, Kotlin | ||
| # compiler PSI stub element types); keep them out of the build-time image heap. The rest of | ||
| # com.facebook is initialized at build time for startup speed. | ||
| com.facebook.ktfmt.cli.EditorConfigResolver | ||
| com.facebook.ktfmt.util.CompatibilityUtilsKt | ||
| kotlin.random.AbstractPlatformRandom | ||
| kotlin.random.Random | ||
| kotlin.random.Random$Default | ||
| kotlin.random.RandomKt | ||
| kotlin.random.XorWowRandom | ||
| kotlin.random.jdk8.PlatformThreadLocalRandom | ||
| kotlin.uuid.SecureRandomHolder |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We only plan to keep the main branch, so I guess we can drop this here, right?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, this is a temporary commit only, so that testing can happen on my fork; I can make sure the build is green before pinging you for a build approval