Skip to content
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

jvm-abi-gen: Remove empty FileClasses from abi #5262

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,15 @@ import org.jetbrains.kotlin.backend.jvm.extensions.ClassGeneratorExtension
import org.jetbrains.kotlin.codegen.inline.coroutines.FOR_INLINE_SUFFIX
import org.jetbrains.kotlin.codegen.`when`.WhenByEnumsMapping
import org.jetbrains.kotlin.descriptors.DescriptorVisibilities
import org.jetbrains.kotlin.ir.declarations.IrClass
import org.jetbrains.kotlin.ir.declarations.IrFunction
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.overrides.isEffectivelyPrivate
import org.jetbrains.kotlin.ir.symbols.UnsafeDuringIrConstructionAPI
import org.jetbrains.kotlin.ir.util.isFileClass
import org.jetbrains.kotlin.ir.util.packageFqName
import org.jetbrains.kotlin.ir.util.primaryConstructor
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.load.java.JvmAnnotationNames
import org.jetbrains.org.objectweb.asm.AnnotationVisitor
import org.jetbrains.org.objectweb.asm.MethodVisitor
import org.jetbrains.org.objectweb.asm.Opcodes
import org.jetbrains.org.objectweb.asm.*
import org.jetbrains.org.objectweb.asm.commons.Method

enum class AbiMethodInfo {
Expand Down Expand Up @@ -63,6 +61,7 @@ class JvmAbiClassBuilderInterceptor(
private val removeDataClassCopyIfConstructorIsPrivate: Boolean,
private val removePrivateClasses: Boolean,
) : ClassGeneratorExtension {
var removedEmptyFileClassesWithoutAliases = mutableMapOf<String?, MutableSet<String>>()
private var abiClassInfoBuilder = JvmAbiClassInfoBuilder(removePrivateClasses)

fun buildAbiClassInfoAndReleaseResources(): Map<String, AbiClassInfo> {
Expand All @@ -82,6 +81,11 @@ class JvmAbiClassBuilderInterceptor(
private val isDataClass = irClass != null && irClass.isData
private val removeClassFromAbi = shouldRemoveFromAbi(irClass, removePrivateClasses)

@OptIn(UnsafeDuringIrConstructionAPI::class)
private val isFileClassWithoutAliases =
irClass?.origin == IrDeclarationOrigin.FILE_CLASS && irClass.declarations.none { it is IrTypeAlias }
private val fileClassPackageName = irClass.takeIf { isFileClassWithoutAliases }?.packageFqName?.asString()

@OptIn(UnsafeDuringIrConstructionAPI::class)
private val primaryConstructorIsNotInAbi =
irClass?.primaryConstructor?.visibility?.let(DescriptorVisibilities::isPrivate) == true
Expand All @@ -92,6 +96,7 @@ class JvmAbiClassBuilderInterceptor(
var keepClassAsIs = false
val methodInfos = mutableMapOf<Method, AbiMethodInfo>()
val maskedMethods = mutableSetOf<Method>() // Methods which should be stripped even if they are marked as KEEP
var hasNoFields = true

override fun defineClass(
version: Int, access: Int, name: String, signature: String?, superName: String, interfaces: Array<out String>
Expand All @@ -110,6 +115,13 @@ class JvmAbiClassBuilderInterceptor(
delegate.visitEnclosingMethod(owner, name, desc)
}

override fun newField(
declaration: IrField?, access: Int, name: String, desc: String, signature: String?, value: Any?,
): FieldVisitor {
hasNoFields = false
return delegate.newField(declaration, access, name, desc, signature, value)
}

override fun newMethod(
declaration: IrFunction?, access: Int, name: String, desc: String, signature: String?, exceptions: Array<out String>?
): MethodVisitor {
Expand Down Expand Up @@ -188,7 +200,12 @@ class JvmAbiClassBuilderInterceptor(
for (method in maskedMethods) {
methodInfos[method] = AbiMethodInfo.STRIP
}
AbiClassInfo.Stripped(methodInfos)
if (isFileClassWithoutAliases && hasNoFields && methodInfos.isEmpty()) {
removedEmptyFileClassesWithoutAliases.getOrPut(fileClassPackageName, ::mutableSetOf).add(internalName)
AbiClassInfo.Deleted
} else {
AbiClassInfo.Stripped(methodInfos)
}
}
}
abiClassInfoBuilder.recordInitialClassInfo(internalName, classInfo, superInterfaces)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ class JvmAbiComponentRegistrar : CompilerPluginRegistrar() {
)
val outputExtension = JvmAbiOutputExtension(
File(outputPath), builderExtension::buildAbiClassInfoAndReleaseResources,
builderExtension.removedEmptyFileClassesWithoutAliases,
messageCollector, configuration.getBoolean(JvmAbiConfigurationKeys.REMOVE_DEBUG_INFO),
removeDataClassCopy,
configuration.getBoolean(JvmAbiConfigurationKeys.PRESERVE_DECLARATION_ORDER),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@

package org.jetbrains.kotlin.jvm.abi

import kotlinx.metadata.jvm.KotlinModuleMetadata
import kotlinx.metadata.jvm.UnstableMetadataApi
import org.jetbrains.kotlin.backend.common.output.OutputFile
import org.jetbrains.kotlin.backend.common.output.OutputFileCollection
import org.jetbrains.kotlin.backend.common.output.SimpleOutputBinaryFile
Expand All @@ -25,6 +27,7 @@ import java.io.File
class JvmAbiOutputExtension(
private val outputPath: File,
private val abiClassInfoBuilder: () -> Map<String, AbiClassInfo>,
private val removedFileClasses: Map<String?, Set<String>>,
private val messageCollector: MessageCollector,
private val removeDebugInfo: Boolean,
private val removeDataClassCopyIfConstructorIsPrivate: Boolean,
Expand All @@ -34,7 +37,7 @@ class JvmAbiOutputExtension(
// We need to wait until the end to produce any output in order to strip classes
// from the InnerClasses attributes.
val outputFiles =
AbiOutputFiles(abiClassInfoBuilder(), factory, removeDebugInfo, removeDataClassCopyIfConstructorIsPrivate, preserveDeclarationOrder)
AbiOutputFiles(abiClassInfoBuilder(), removedFileClasses, factory, removeDebugInfo, removeDataClassCopyIfConstructorIsPrivate, preserveDeclarationOrder)
if (outputPath.extension == "jar") {
// We don't include the runtime or main class in interface jars and always reset time stamps.
CompileEnvironmentUtil.writeToJar(
Expand All @@ -55,6 +58,7 @@ class JvmAbiOutputExtension(

private class AbiOutputFiles(
val abiClassInfos: Map<String, AbiClassInfo>,
val removedFileClasses: Map<String?, Set<String>>,
val outputFiles: OutputFileCollection,
val removeDebugInfo: Boolean,
val removeCopyAlongWithConstructor: Boolean,
Expand All @@ -69,9 +73,13 @@ class JvmAbiOutputExtension(
}

override fun asList(): List<OutputFile> {
val metadata = outputFiles.asList().filter {
!it.relativePath.endsWith(".class")
}.sortedBy { it.relativePath }
val metadata = outputFiles
.asList()
.asSequence()
.filter { !it.relativePath.endsWith(".class") }
.sortedBy { it.relativePath }
.map { outputFile -> removeFileClassesFromModuleMetadata(outputFile, removedFileClasses) }
.toList()

val classFiles = abiClassInfos.keys.sorted().mapNotNull { internalName ->
// Note that outputFile may be null, e.g., for empty $DefaultImpls classes in the JVM backend.
Expand Down Expand Up @@ -244,3 +252,25 @@ private class DebugInfoRemovingMethodVisitor(visitor: MethodVisitor) : MethodVis

override fun visitLocalVariable(name: String?, descriptor: String?, signature: String?, start: Label?, end: Label?, index: Int) {}
}

@OptIn(UnstableMetadataApi::class)
private fun removeFileClassesFromModuleMetadata(outputFile: OutputFile, removedFileClasses: Map<String?, Set<String>>): OutputFile {
if (removedFileClasses.isEmpty()) return outputFile

val metadata = KotlinModuleMetadata.read(outputFile.asByteArray())
val iterator = metadata.kmModule.packageParts.iterator()

var changed = false

while (iterator.hasNext()) {
val (pkg, parts) = iterator.next()
val removedClasses = removedFileClasses[pkg].orEmpty()

val oldSize = parts.fileFacades.size
parts.fileFacades.removeAll { it in removedClasses }
changed = changed || oldSize != parts.fileFacades.size

if (parts.fileFacades.isEmpty() && parts.multiFileClassParts.isEmpty()) iterator.remove()
}
return if (changed) SimpleOutputBinaryFile(outputFile.sourceFiles, outputFile.relativePath, metadata.write()) else outputFile
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package test

private fun hostingClassShouldNotAffectAbi() = Unit

class JustClass
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package test

class JustClass