JVM: introduce JvmBackendConfig

Move language version settings, compiler configuration and different
flags there, and use this config everywhere in both backends instead of
GenerationState.

This will hopefully make GenerationState less of a "god object" and
remove the need to have it available everywhere, in particular in JVM IR
lowerings code, in the future.

Also, future refactorings will make it easier to inject backend-specific
behavior into common code, so that we would not need to handle support
of new features in the old backend.
This commit is contained in:
Alexander Udalov
2023-07-21 18:18:42 +02:00
committed by Space Team
parent b6f8991072
commit 72d048bd62
70 changed files with 265 additions and 237 deletions
@@ -144,7 +144,7 @@ public class ClassFileFactory implements OutputFileCollection {
if (state.getLanguageVersionSettings().getFlag(JvmAnalysisFlags.getStrictMetadataVersionSemantics())) {
flags |= ModuleMapping.STRICT_METADATA_VERSION_SEMANTICS_FLAG;
}
return ModuleMappingKt.serializeToByteArray(moduleProto, state.getMetadataVersion(), flags);
return ModuleMappingKt.serializeToByteArray(moduleProto, state.getConfig().getMetadataVersion(), flags);
}
@Override
@@ -173,7 +173,7 @@ public class ClosureCodegen extends MemberCodegen<KtElement> {
v.defineClass(
element,
state.getClassFileVersion(),
state.getConfig().getClassFileVersion(),
ACC_FINAL | ACC_SUPER | visibilityFlag | getSyntheticAccessFlagForLambdaClass(classDescriptor),
asmType.getInternalName(),
sw.makeJavaGenericSignature(),
@@ -53,7 +53,7 @@ class CodeFragmentCodegen private constructor(
override fun generateDeclaration() {
v.defineClass(
codeFragment,
state.classFileVersion,
state.config.classFileVersion,
ACC_PUBLIC or ACC_SUPER,
info.classType.internalName,
null,
@@ -676,7 +676,7 @@ public class DescriptorAsmUtil {
@NotNull FunctionDescriptor descriptor,
@NotNull FrameMap frameMap
) {
if (state.isParamAssertionsDisabled()) return;
if (state.getConfig().isParamAssertionsDisabled()) return;
// currently when resuming a suspend function we pass default values instead of real arguments (i.e. nulls for references)
if (descriptor.isSuspend()) return;
@@ -688,7 +688,7 @@ public class DescriptorAsmUtil {
// Such functions can be invoked in operator conventions desugaring,
// which is currently done on ad hoc basis in ExpressionCodegen.
if (state.isReceiverAssertionsDisabled()) return;
if (state.getConfig().isReceiverAssertionsDisabled()) return;
if (descriptor.isOperator()) {
ReceiverParameterDescriptor receiverParameter = descriptor.getExtensionReceiverParameter();
if (receiverParameter != null) {
@@ -737,7 +737,7 @@ public class DescriptorAsmUtil {
}
value.put(asmType, v);
v.visitLdcInsn(name);
String methodName = state.getUnifiedNullChecks() ? "checkNotNullParameter" : "checkParameterIsNotNull";
String methodName = state.getConfig().getUnifiedNullChecks() ? "checkNotNullParameter" : "checkParameterIsNotNull";
v.invokestatic(IntrinsicMethods.INTRINSICS_CLASS_NAME, methodName, "(Ljava/lang/Object;Ljava/lang/String;)V", false);
}
}
@@ -748,7 +748,7 @@ public class DescriptorAsmUtil {
@NotNull StackValue stackValue,
@Nullable RuntimeAssertionInfo runtimeAssertionInfo
) {
if (state.isCallAssertionsDisabled()) return stackValue;
if (state.getConfig().isCallAssertionsDisabled()) return stackValue;
if (runtimeAssertionInfo == null || !runtimeAssertionInfo.getNeedNotNullAssertion()) return stackValue;
return new StackValue(stackValue.type, stackValue.kotlinType) {
@@ -760,7 +760,8 @@ public class DescriptorAsmUtil {
if (innerType.getSort() == Type.OBJECT || innerType.getSort() == Type.ARRAY) {
v.dup();
v.visitLdcInsn(runtimeAssertionInfo.getMessage());
String methodName = state.getUnifiedNullChecks() ? "checkNotNullExpressionValue" : "checkExpressionValueIsNotNull";
String methodName =
state.getConfig().getUnifiedNullChecks() ? "checkNotNullExpressionValue" : "checkExpressionValueIsNotNull";
v.invokestatic(IntrinsicMethods.INTRINSICS_CLASS_NAME, methodName, "(Ljava/lang/Object;Ljava/lang/String;)V", false);
}
StackValue.coerce(innerType, innerKotlinType, type, kotlinType, v);
@@ -13,7 +13,6 @@ import com.intellij.psi.tree.IElementType;
import com.intellij.util.ArrayUtil;
import com.intellij.util.Function;
import com.intellij.util.containers.Stack;
import kotlin.Pair;
import kotlin.Unit;
import kotlin.collections.CollectionsKt;
import kotlin.text.StringsKt;
@@ -38,7 +37,6 @@ import org.jetbrains.kotlin.codegen.range.RangeValue;
import org.jetbrains.kotlin.codegen.range.RangeValuesKt;
import org.jetbrains.kotlin.codegen.range.forLoop.ForLoopGenerator;
import org.jetbrains.kotlin.codegen.signature.BothSignatureWriter;
import org.jetbrains.kotlin.codegen.signature.JvmSignatureWriter;
import org.jetbrains.kotlin.codegen.state.GenerationState;
import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper;
import org.jetbrains.kotlin.codegen.when.SwitchCodegen;
@@ -62,14 +60,9 @@ import org.jetbrains.kotlin.name.Name;
import org.jetbrains.kotlin.psi.*;
import org.jetbrains.kotlin.psi.psiUtil.PsiUtilsKt;
import org.jetbrains.kotlin.resolve.*;
import org.jetbrains.kotlin.resolve.calls.util.CallResolverUtilKt;
import org.jetbrains.kotlin.resolve.calls.util.CallUtilKt;
import org.jetbrains.kotlin.resolve.calls.inference.CapturedTypeConstructorKt;
import org.jetbrains.kotlin.resolve.calls.model.*;
import org.jetbrains.kotlin.resolve.calls.util.CallMaker;
import org.jetbrains.kotlin.resolve.calls.util.FakeCallableDescriptorForObject;
import org.jetbrains.kotlin.resolve.calls.util.FakeCallableDescriptorForTypeAliasObject;
import org.jetbrains.kotlin.resolve.calls.util.UnderscoreUtilKt;
import org.jetbrains.kotlin.resolve.calls.util.*;
import org.jetbrains.kotlin.resolve.checkers.PrimitiveNumericComparisonInfo;
import org.jetbrains.kotlin.resolve.constants.*;
import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluatorKt;
@@ -857,12 +850,12 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
@Nullable
public ConstantValue<?> getCompileTimeConstant(@NotNull KtExpression expression) {
return getCompileTimeConstant(expression, bindingContext, state.getShouldInlineConstVals());
return getCompileTimeConstant(expression, bindingContext, state.getConfig().getShouldInlineConstVals());
}
@Nullable
public ConstantValue<?> getPrimitiveOrStringCompileTimeConstant(@NotNull KtExpression expression) {
return getPrimitiveOrStringCompileTimeConstant(expression, bindingContext, state.getShouldInlineConstVals());
return getPrimitiveOrStringCompileTimeConstant(expression, bindingContext, state.getConfig().getShouldInlineConstVals());
}
@Nullable
@@ -1686,7 +1679,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
CallableMemberDescriptor descriptor = getContext().getContextDescriptor();
NonLocalReturnInfo nonLocalReturn = getNonLocalReturnInfo(descriptor, expression);
boolean isNonLocalReturn = nonLocalReturn != null;
if (isNonLocalReturn && state.isInlineDisabled()) {
if (isNonLocalReturn && state.getConfig().isInlineDisabled()) {
state.getDiagnostics().report(Errors.NON_LOCAL_RETURN_IN_DISABLED_INLINE.on(expression));
genThrow(v, "java/lang/UnsupportedOperationException",
"Non-local returns are not allowed with inlining disabled");
@@ -2309,9 +2302,9 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
PropertyDescriptor originalPropertyDescriptor = DescriptorUtils.unwrapFakeOverride(propertyDescriptor);
boolean directAccessToGetter =
couldUseDirectAccessToProperty(propertyDescriptor, true, isDelegatedProperty, context, state.getShouldInlineConstVals());
couldUseDirectAccessToProperty(propertyDescriptor, true, isDelegatedProperty, context, state.getConfig().getShouldInlineConstVals());
boolean directAccessToSetter =
couldUseDirectAccessToProperty(propertyDescriptor, false, isDelegatedProperty, context, state.getShouldInlineConstVals());
couldUseDirectAccessToProperty(propertyDescriptor, false, isDelegatedProperty, context, state.getConfig().getShouldInlineConstVals());
if (fieldAccessorKind == AccessorKind.LATEINIT_INTRINSIC) {
skipPropertyAccessors =
@@ -2707,8 +2700,8 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
@NotNull CallGenerator callGenerator,
@NotNull ArgumentGenerator argumentGenerator
) {
if (AssertCodegenUtilKt.isAssertCall(resolvedCall) && !state.getAssertionsMode().equals(JVMAssertionsMode.LEGACY)) {
AssertCodegenUtilKt.generateAssert(state.getAssertionsMode(), resolvedCall, this, parentCodegen);
if (AssertCodegenUtilKt.isAssertCall(resolvedCall) && !state.getConfig().getAssertionsMode().equals(JVMAssertionsMode.LEGACY)) {
AssertCodegenUtilKt.generateAssert(state.getConfig().getAssertionsMode(), resolvedCall, this, parentCodegen);
return;
}
@@ -2778,7 +2771,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
KotlinType returnType = resolvedCall.getResultingDescriptor().getReturnType();
if (returnType != null && KotlinBuiltIns.isNothing(returnType)) {
if (state.getUseKotlinNothingValueException()) {
if (state.getConfig().getUseKotlinNothingValueException()) {
v.anew(Type.getObjectType("kotlin/KotlinNothingValueException"));
v.dup();
v.invokespecial("kotlin/KotlinNothingValueException", "<init>", "()V", false);
@@ -2881,7 +2874,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
// We should inline callable containing reified type parameters even if inline is disabled
// because they may contain something to reify and straight call will probably fail at runtime
boolean shouldInline = isInline && (!state.isInlineDisabled() || InlineUtil.containsReifiedTypeParameters(descriptor));
boolean shouldInline = isInline && (!state.getConfig().isInlineDisabled() || InlineUtil.containsReifiedTypeParameters(descriptor));
if (!shouldInline) return defaultCallGenerator;
FunctionDescriptor original =
@@ -2994,7 +2987,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
else if (receiverValue instanceof ExpressionReceiver) {
ExpressionReceiver expressionReceiver = (ExpressionReceiver) receiverValue;
StackValue stackValue = gen(expressionReceiver.getExpression());
if (!state.isReceiverAssertionsDisabled()) {
if (!state.getConfig().isReceiverAssertionsDisabled()) {
RuntimeAssertionInfo runtimeAssertionInfo =
bindingContext.get(JvmBindingContextSlices.RECEIVER_RUNTIME_ASSERTION_INFO, expressionReceiver);
stackValue = genNotNullAssertions(state, stackValue, runtimeAssertionInfo);
@@ -4402,7 +4395,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
return StackValue.operation(base.type, base.kotlinType, v -> {
base.put(base.type, base.kotlinType, v);
v.dup();
if (state.getUnifiedNullChecks()) {
if (state.getConfig().getUnifiedNullChecks()) {
v.invokestatic(IntrinsicMethods.INTRINSICS_CLASS_NAME, "checkNotNull", "(Ljava/lang/Object;)V", false);
} else {
Label ok = new Label();
@@ -5162,7 +5155,7 @@ The "returned" value of try expression with no finally is either the last expres
}
CodegenUtilKt.generateAsCast(
v, rightKotlinType, boxedRightType, safeAs, state.getUnifiedNullChecks()
v, rightKotlinType, boxedRightType, safeAs, state.getConfig().getUnifiedNullChecks()
);
return Unit.INSTANCE;
@@ -203,7 +203,7 @@ public class FunctionsFromAnyGeneratorImpl extends FunctionsFromAnyGenerator {
iv.ifnull(ifNull);
}
genHashCode(mv, iv, asmType, generationState.getTarget());
genHashCode(mv, iv, asmType, generationState.getConfig().getTarget());
if (ifNull != null) {
Label end = new Label();
@@ -232,7 +232,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
v.defineClass(
myClass.getPsiOrParent(),
state.getClassFileVersion(),
state.getConfig().getClassFileVersion(),
access,
signature.getName(),
signature.getJavaGenericSignature(),
@@ -538,7 +538,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
) {
iv.load(index, classAsmType);
if (couldUseDirectAccessToProperty(propertyDescriptor, /* forGetter = */ true,
/* isDelegated = */ false, context, state.getShouldInlineConstVals())) {
/* isDelegated = */ false, context, state.getConfig().getShouldInlineConstVals())) {
KotlinType kotlinType = propertyDescriptor.getType();
Type type = state.getTypeMapper().mapType(kotlinType);
String fieldName = ((FieldOwnerContext) context.getParentContext()).getFieldName(propertyDescriptor, false);
@@ -47,9 +47,9 @@ class InterfaceImplBodyCodegen(
val codegenFlags = ACC_PUBLIC or ACC_FINAL or ACC_SUPER
val flags = if (state.classBuilderMode == ClassBuilderMode.LIGHT_CLASSES) codegenFlags or ACC_STATIC else codegenFlags
v.defineClass(
myClass.psiOrParent, state.classFileVersion, flags,
defaultImplType.internalName,
null, "java/lang/Object", ArrayUtil.EMPTY_STRING_ARRAY
myClass.psiOrParent, state.config.classFileVersion, flags,
defaultImplType.internalName,
null, "java/lang/Object", ArrayUtil.EMPTY_STRING_ARRAY
)
v.visitSource(myClass.containingKtFile.name, null)
}
@@ -191,7 +191,7 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
v.visitSMAP(getOrCreateSourceMapper(), !state.getLanguageVersionSettings().supportsFeature(LanguageFeature.CorrectSourceMappingSyntax));
}
v.done(state.getGenerateSmapCopyToAnnotation());
v.done(state.getConfig().getGenerateSmapCopyToAnnotation());
}
public void genSimpleMember(@NotNull KtDeclaration declaration) {
@@ -597,7 +597,9 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
KtExpression initializer = property.getInitializer();
ConstantValue<?> initializerValue =
initializer != null ? ExpressionCodegen.getCompileTimeConstant(initializer, bindingContext, state.getShouldInlineConstVals()) : null;
initializer != null
? ExpressionCodegen.getCompileTimeConstant(initializer, bindingContext, state.getConfig().getShouldInlineConstVals())
: null;
// we must write constant values for fields in light classes,
// because Java's completion for annotation arguments uses this information
if (initializerValue == null) return state.getClassBuilderMode().generateBodies;
@@ -692,7 +694,7 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
iv.dup();
List<Type> superCtorArgTypes = new ArrayList<>();
if (state.getGenerateOptimizedCallableReferenceSuperClasses()) {
if (state.getConfig().getGenerateOptimizedCallableReferenceSuperClasses()) {
CallableReferenceUtilKt.generateCallableReferenceDeclarationContainerClass(iv, property, state);
superCtorArgTypes.add(JAVA_CLASS_TYPE);
} else {
@@ -706,7 +708,7 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
superCtorArgTypes.add(JAVA_STRING_TYPE);
superCtorArgTypes.add(JAVA_STRING_TYPE);
if (state.getGenerateOptimizedCallableReferenceSuperClasses()) {
if (state.getConfig().getGenerateOptimizedCallableReferenceSuperClasses()) {
iv.aconst(CallableReferenceUtilKt.getCallableReferenceTopLevelFlag(property));
superCtorArgTypes.add(Type.INT_TYPE);
}
@@ -754,7 +756,7 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
}
protected void initDefaultSourceMappingIfNeeded() {
if (state.isInlineDisabled()) return;
if (state.getConfig().isInlineDisabled()) return;
CodegenContext parentContext = context.getParentContext();
while (parentContext != null) {
@@ -140,7 +140,7 @@ class MultifileClassCodegenImpl(
}
defineClass(
singleSourceFile, state.classFileVersion, attributes,
singleSourceFile, state.config.classFileVersion, attributes,
facadeClassType.internalName, null, superClassForFacade, emptyArray()
)
if (singleSourceFile != null) {
@@ -344,7 +344,7 @@ class MultifileClassCodegenImpl(
}
private fun done() {
classBuilder.done(state.generateSmapCopyToAnnotation)
classBuilder.done(state.config.generateSmapCopyToAnnotation)
if (classBuilder.isComputed) {
state.afterIndependentPart()
}
@@ -73,7 +73,7 @@ class MultifileClassPartCodegen(
val access = if (shouldGeneratePartHierarchy) 0 else Opcodes.ACC_SYNTHETIC or Opcodes.ACC_FINAL
v.defineClass(
element, state.classFileVersion, access or Opcodes.ACC_SUPER, partType.internalName, null, superClassInternalName,
element, state.config.classFileVersion, access or Opcodes.ACC_SUPER, partType.internalName, null, superClassInternalName,
ArrayUtil.EMPTY_STRING_ARRAY
)
v.visitSource(element.name, null)
@@ -77,7 +77,7 @@ public class PackagePartCodegen extends MemberCodegen<KtFile> {
}
}
v.defineClass(element, state.getClassFileVersion(),
v.defineClass(element, state.getConfig().getClassFileVersion(),
ACC_PUBLIC | ACC_FINAL | ACC_SUPER | (isSynthetic ? ACC_SYNTHETIC : 0),
packagePartType.getInternalName(),
null,
@@ -299,7 +299,7 @@ public class PropertyCodegen {
KtExpression defaultValue = loadAnnotationArgumentDefaultValue(parameter, descriptor, expectedAnnotationConstructor);
if (defaultValue != null) {
ConstantValue<?> constant = ExpressionCodegen.getCompileTimeConstant(
defaultValue, bindingContext, true, state.getShouldInlineConstVals());
defaultValue, bindingContext, true, state.getConfig().getShouldInlineConstVals());
assert !state.getClassBuilderMode().generateBodies || constant != null
: "Default value for annotation parameter should be compile time value: " + defaultValue.getText();
if (constant != null) {
@@ -91,7 +91,7 @@ class PropertyReferenceCodegen(
override fun generateDeclaration() {
v.defineClass(
element,
state.classFileVersion,
state.config.classFileVersion,
ACC_FINAL or ACC_SUPER or
DescriptorAsmUtil.getVisibilityAccessFlagForClass(classDescriptor) or
DescriptorAsmUtil.getSyntheticAccessFlagForLambdaClass(classDescriptor),
@@ -129,7 +129,7 @@ public class SamWrapperCodegen {
: new String[] {samAsmType.getInternalName()};
cv.defineClass(
file,
state.getClassFileVersion(),
state.getConfig().getClassFileVersion(),
classFlags,
asmType.getInternalName(),
null,
@@ -166,7 +166,7 @@ public class SamWrapperCodegen {
generateDelegatesToDefaultImpl(asmType, classDescriptor, samType.getClassDescriptor(), functionCodegen, state);
}
cv.done(state.getGenerateSmapCopyToAnnotation());
cv.done(state.getConfig().getGenerateSmapCopyToAnnotation());
return asmType;
}
@@ -43,7 +43,7 @@ class ScriptCodegen private constructor(
override fun generateDeclaration() {
v.defineClass(
scriptDeclaration,
state.classFileVersion,
state.config.classFileVersion,
ACC_PUBLIC or ACC_SUPER,
classAsmType.internalName,
null,
@@ -1806,7 +1806,7 @@ public abstract class StackValue {
return inlineConstant(type, kotlinType, v);
}
if (descriptor.isConst() && codegen.getState().getShouldInlineConstVals()) {
if (descriptor.isConst() && codegen.getState().getConfig().getShouldInlineConstVals()) {
return inlineConstant(type, kotlinType, v);
}
@@ -17,7 +17,6 @@ import org.jetbrains.org.objectweb.asm.Handle
import org.jetbrains.org.objectweb.asm.Opcodes
import org.jetbrains.org.objectweb.asm.Type
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter
import java.lang.StringBuilder
class StringConcatGenerator(val mode: JvmStringConcat, val mv: InstructionAdapter) {
@@ -236,7 +235,6 @@ class StringConcatGenerator(val mode: JvmStringConcat, val mv: InstructionAdapte
}
fun create(state: GenerationState, mv: InstructionAdapter) =
StringConcatGenerator(state.runtimeStringConcat, mv)
StringConcatGenerator(state.config.runtimeStringConcat, mv)
}
}
@@ -593,7 +593,7 @@ private fun generateLambdaForRunSuspend(
)
lambdaBuilder.defineClass(
originElement, state.classFileVersion,
originElement, state.config.classFileVersion,
ACC_FINAL or ACC_SUPER or ACC_SYNTHETIC,
internalName, null,
AsmTypes.LAMBDA.internalName,
@@ -676,7 +676,7 @@ private fun generateLambdaForRunSuspend(
writeSyntheticClassMetadata(lambdaBuilder, state, false)
lambdaBuilder.done(state.generateSmapCopyToAnnotation)
lambdaBuilder.done(state.config.generateSmapCopyToAnnotation)
return lambdaBuilder.thisName
}
@@ -30,7 +30,7 @@ fun generateParameterNames(
state: GenerationState,
isSynthetic: Boolean
) {
if (!state.generateParametersMetadata || isSynthetic) {
if (!state.config.generateParametersMetadata || isSynthetic) {
return
}
@@ -59,7 +59,9 @@ class AnonymousObjectTransformer(
createClassReader().accept(object : ClassVisitor(Opcodes.API_VERSION, classBuilder.visitor) {
override fun visit(version: Int, access: Int, name: String, signature: String?, superName: String, interfaces: Array<String>) {
classBuilder.defineClass(null, maxOf(version, state.classFileVersion), access, name, signature, superName, interfaces)
classBuilder.defineClass(
null, maxOf(version, state.config.classFileVersion), access, name, signature, superName, interfaces
)
if (superName.isCoroutineSuperClass()) {
inliningContext.isContinuation = true
}
@@ -229,7 +231,7 @@ class AnonymousObjectTransformer(
if (continuationClassName == transformationInfo.oldClassName) {
coroutineTransformer.registerClassBuilder(continuationClassName)
} else {
classBuilder.done(state.generateSmapCopyToAnnotation)
classBuilder.done(state.config.generateSmapCopyToAnnotation)
}
return transformationResult
@@ -206,7 +206,7 @@ class MethodInliner(
}
for (classBuilder in childInliningContext.continuationBuilders.values) {
classBuilder.done(inliningContext.state.generateSmapCopyToAnnotation)
classBuilder.done(inliningContext.state.config.generateSmapCopyToAnnotation)
}
} else {
result.addNotChangedClass(oldClassName)
@@ -65,7 +65,9 @@ class WhenMappingTransformer(
val fieldNode = transformationInfo.fieldNode
classReader.accept(object : ClassVisitor(Opcodes.API_VERSION, classBuilder.visitor) {
override fun visit(version: Int, access: Int, name: String, signature: String?, superName: String, interfaces: Array<String>) {
classBuilder.defineClass(null, maxOf(version, state.classFileVersion), access, name, signature, superName, interfaces)
classBuilder.defineClass(
null, maxOf(version, state.config.classFileVersion), access, name, signature, superName, interfaces
)
}
override fun visitField(access: Int, name: String, desc: String, signature: String?, value: Any?): FieldVisitor? {
@@ -104,7 +106,7 @@ class WhenMappingTransformer(
transformedClinit.signature, transformedClinit.exceptions.toTypedArray()
)
transformedClinit.accept(result)
classBuilder.done(state.generateSmapCopyToAnnotation)
classBuilder.done(state.config.generateSmapCopyToAnnotation)
return transformationResult
}
@@ -44,7 +44,7 @@ class PsiInlineCodegen(
codegen, state, signature, typeParameterMappings, sourceCompiler,
ReifiedTypeInliner(
typeParameterMappings, PsiInlineIntrinsicsSupport(state, reportErrorsOn), codegen.typeSystem,
state.languageVersionSettings, state.unifiedNullChecks
state.languageVersionSettings, state.config.unifiedNullChecks
),
), CallGenerator {
override fun generateAssertField() =
@@ -46,7 +46,7 @@ class PsiInlineIntrinsicsSupport(
}
private fun generateFunctionReference(v: InstructionAdapter, descriptor: FunctionDescriptor) {
check(state.generateOptimizedCallableReferenceSuperClasses) {
check(state.config.generateOptimizedCallableReferenceSuperClasses) {
"typeOf() of a non-reified type parameter is only allowed if optimized callable references are enabled.\n" +
"Please make sure API version is set to 1.4, and -Xno-optimized-callable-references is NOT used.\n" +
"Container: $descriptor"
@@ -61,11 +61,13 @@ class SamWrapperTransformer(transformationInfo: SamWrapperTransformationInfo, pr
classReader.accept(object : ClassVisitor(Opcodes.API_VERSION, classBuilder.visitor) {
override fun visit(version: Int, access: Int, name: String, signature: String?, superName: String, interfaces: Array<String>) {
classBuilder.defineClass(null, maxOf(version, state.classFileVersion), access, name, signature, superName, interfaces)
classBuilder.defineClass(
null, maxOf(version, state.config.classFileVersion), access, name, signature, superName, interfaces
)
}
}, ClassReader.SKIP_FRAMES)
classBuilder.done(inliningContext.state.generateSmapCopyToAnnotation)
classBuilder.done(inliningContext.state.config.generateSmapCopyToAnnotation)
return transformationResult
}
@@ -142,7 +142,7 @@ class CoroutineTransformer(
}
fun replaceFakesWithReals(node: MethodNode) {
findFakeContinuationConstructorClassName(node)?.let(::unregisterClassBuilder)?.done(state.generateSmapCopyToAnnotation)
findFakeContinuationConstructorClassName(node)?.let(::unregisterClassBuilder)?.done(state.config.generateSmapCopyToAnnotation)
replaceFakeContinuationsWithRealOnes(
node, if (!inliningContext.isContinuation) getLastParameterIndex(node.desc, node.access) else 0
)
@@ -84,7 +84,7 @@ private fun <KT : KotlinTypeMarker> TypeSystemCommonBackendContext.generateTypeO
intrinsicsSupport.reportSuspendTypeUnsupported()
}
if (intrinsicsSupport.state.stableTypeOf) {
if (intrinsicsSupport.state.config.stableTypeOf) {
if (intrinsicsSupport.isMutableCollectionType(type)) {
v.invokestatic(REFLECTION, "mutableCollectionType", Type.getMethodDescriptor(K_TYPE, K_TYPE), false)
} else if (type.typeConstructor().isNothingConstructor()) {
@@ -23,7 +23,7 @@ import org.jetbrains.org.objectweb.asm.tree.analysis.BasicVerifier
class MethodVerifier(private val checkPoint: String, private val generationState: GenerationState) : MethodTransformer() {
override fun transform(internalClassName: String, methodNode: MethodNode) {
if (!generationState.shouldValidateBytecode) return
if (!generationState.config.shouldValidateBytecode) return
try {
analyze(internalClassName, methodNode, BasicVerifier())
} catch (e: Throwable) {
@@ -69,7 +69,7 @@ class OptimizationMethodVisitor(
normalizationMethodTransformer.transform("fake", methodNode)
UninitializedStoresProcessor(methodNode).run()
if (!mandatoryTransformationsOnly && canBeOptimized(methodNode) && !generationState.disableOptimization) {
if (!mandatoryTransformationsOnly && canBeOptimized(methodNode) && !generationState.config.disableOptimization) {
optimizationTransformer.transform("fake", methodNode)
}
@@ -49,17 +49,17 @@ class JvmSerializerExtension @JvmOverloads constructor(
private val globalBindings = state.globalSerializationBindings
private val codegenBinding = state.bindingContext
override val stringTable = JvmCodegenStringTable(typeMapper)
private val useTypeTable = state.useTypeTableInSerializer
private val useTypeTable = state.config.useTypeTableInSerializer
private val moduleName = state.moduleName
private val classBuilderMode = state.classBuilderMode
private val languageVersionSettings = state.languageVersionSettings
private val isParamAssertionsDisabled = state.isParamAssertionsDisabled
private val unifiedNullChecks = state.unifiedNullChecks
private val functionsWithInlineClassReturnTypesMangled = state.functionsWithInlineClassReturnTypesMangled
override val metadataVersion = state.metadataVersion
private val isParamAssertionsDisabled = state.config.isParamAssertionsDisabled
private val unifiedNullChecks = state.config.unifiedNullChecks
private val functionsWithInlineClassReturnTypesMangled = state.config.functionsWithInlineClassReturnTypesMangled
override val metadataVersion = state.config.metadataVersion
private val jvmDefaultMode = state.jvmDefaultMode
private val approximator = state.typeApproximator
private val useOldManglingScheme = state.useOldManglingSchemeForFunctionsWithInlineClassesInSignatures
private val useOldManglingScheme = state.config.useOldManglingSchemeForFunctionsWithInlineClassesInSignatures
private val signatureSerializer = JvmSignatureSerializerImpl(stringTable)
override fun shouldUseTypeTable(): Boolean = useTypeTable
@@ -52,7 +52,6 @@ import org.jetbrains.kotlin.serialization.deserialization.DeserializationConfigu
import org.jetbrains.kotlin.storage.LockBasedStorageManager
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeApproximator
import org.jetbrains.kotlin.utils.metadataVersion
import org.jetbrains.org.objectweb.asm.Type
import java.io.File
@@ -179,7 +178,8 @@ class GenerationState private constructor(
}
}
val languageVersionSettings = configuration.languageVersionSettings
val config = JvmBackendConfig(configuration)
val languageVersionSettings = config.languageVersionSettings
val inlineCache: InlineCache = InlineCache()
@@ -219,7 +219,7 @@ class GenerationState private constructor(
}
}
val extraJvmDiagnosticsTrace: BindingTrace =
private val extraJvmDiagnosticsTrace: BindingTrace =
DelegatingBindingTrace(
originalFrontendBindingContext, "For extra diagnostics in ${this::class.java}", false,
customSuppressCache = if (isIrBackend) OnDemandSuppressCache(originalFrontendBindingContext) else null,
@@ -234,29 +234,6 @@ class GenerationState private constructor(
extraJvmDiagnosticsTrace.bindingContext.diagnostics
}
val useOldManglingSchemeForFunctionsWithInlineClassesInSignatures =
configuration.getBoolean(JVMConfigurationKeys.USE_OLD_INLINE_CLASSES_MANGLING_SCHEME) ||
languageVersionSettings.languageVersion.run { major == 1 && minor < 4 }
val target = configuration.get(JVMConfigurationKeys.JVM_TARGET) ?: JvmTarget.DEFAULT
val runtimeStringConcat =
if (target.majorVersion >= JvmTarget.JVM_9.majorVersion)
configuration.get(JVMConfigurationKeys.STRING_CONCAT) ?: JvmStringConcat.INDY_WITH_CONSTANTS
else JvmStringConcat.INLINE
val samConversionsScheme: JvmClosureGenerationScheme =
configuration.get(JVMConfigurationKeys.SAM_CONVERSIONS)
?: if (languageVersionSettings.supportsFeature(LanguageFeature.SamWrapperClassesAreSynthetic))
JvmClosureGenerationScheme.INDY
else
JvmClosureGenerationScheme.CLASS
val lambdasScheme: JvmClosureGenerationScheme =
configuration.get(JVMConfigurationKeys.LAMBDAS)
?: if (languageVersionSettings.supportsFeature(LanguageFeature.LightweightLambdas))
JvmClosureGenerationScheme.INDY
else JvmClosureGenerationScheme.CLASS
val moduleName: String = moduleName ?: JvmCodegenUtil.getModuleName(module)
val classBuilderMode: ClassBuilderMode = builderFactory.classBuilderMode
val bindingTrace: BindingTrace = DelegatingBindingTrace(
@@ -270,27 +247,18 @@ class GenerationState private constructor(
classBuilderMode,
this.moduleName,
languageVersionSettings,
useOldManglingSchemeForFunctionsWithInlineClassesInSignatures,
target,
config.useOldManglingSchemeForFunctionsWithInlineClassesInSignatures,
config.target,
isIrBackend
)
val canReplaceStdlibRuntimeApiBehavior = languageVersionSettings.apiVersion <= ApiVersion.parse(KotlinVersion.CURRENT.toString())!!
val intrinsics: IntrinsicMethods = IntrinsicMethods(canReplaceStdlibRuntimeApiBehavior)
val generateOptimizedCallableReferenceSuperClasses =
languageVersionSettings.apiVersion >= ApiVersion.KOTLIN_1_4 &&
!configuration.getBoolean(JVMConfigurationKeys.NO_OPTIMIZED_CALLABLE_REFERENCES)
val useKotlinNothingValueException =
languageVersionSettings.apiVersion >= ApiVersion.KOTLIN_1_4 &&
!configuration.getBoolean(JVMConfigurationKeys.NO_KOTLIN_NOTHING_VALUE_EXCEPTION)
// In 1.6, `typeOf` became stable and started to rely on a few internal stdlib functions which were missing before 1.6.
val stableTypeOf = languageVersionSettings.apiVersion >= ApiVersion.KOTLIN_1_6
val intrinsics: IntrinsicMethods =
IntrinsicMethods(languageVersionSettings.apiVersion <= ApiVersion.parse(KotlinVersion.CURRENT.toString())!!)
val samWrapperClasses: SamWrapperClasses = SamWrapperClasses(this)
val globalInlineContext: GlobalInlineContext = GlobalInlineContext(diagnostics)
val mappingsClassesForWhenByEnum: MappingsClassesForWhenByEnum = MappingsClassesForWhenByEnum(this)
val jvmRuntimeTypes: JvmRuntimeTypes = JvmRuntimeTypes(
module, languageVersionSettings, generateOptimizedCallableReferenceSuperClasses
module, languageVersionSettings, config.generateOptimizedCallableReferenceSuperClasses
)
val factory: ClassFileFactory
private var duplicateSignatureFactory: BuilderFactoryForDuplicateSignatureDiagnostics? = null
@@ -307,53 +275,10 @@ class GenerationState private constructor(
var resultType: KotlinType? = null
}
val isCallAssertionsDisabled: Boolean = configuration.getBoolean(JVMConfigurationKeys.DISABLE_CALL_ASSERTIONS)
val isReceiverAssertionsDisabled: Boolean =
configuration.getBoolean(JVMConfigurationKeys.DISABLE_RECEIVER_ASSERTIONS) ||
!languageVersionSettings.supportsFeature(LanguageFeature.NullabilityAssertionOnExtensionReceiver)
val isParamAssertionsDisabled: Boolean = configuration.getBoolean(JVMConfigurationKeys.DISABLE_PARAM_ASSERTIONS)
val assertionsMode: JVMAssertionsMode = configuration.get(JVMConfigurationKeys.ASSERTIONS_MODE, JVMAssertionsMode.DEFAULT)
val isInlineDisabled: Boolean = configuration.getBoolean(CommonConfigurationKeys.DISABLE_INLINE)
val useTypeTableInSerializer: Boolean = configuration.getBoolean(JVMConfigurationKeys.USE_TYPE_TABLE)
val unifiedNullChecks: Boolean =
languageVersionSettings.apiVersion >= ApiVersion.KOTLIN_1_4 &&
!configuration.getBoolean(JVMConfigurationKeys.NO_UNIFIED_NULL_CHECKS)
val noSourceCodeInNotNullAssertionExceptions: Boolean =
(languageVersionSettings.supportsFeature(LanguageFeature.NoSourceCodeInNotNullAssertionExceptions)
// This check is needed because we generate calls to `Intrinsics.checkNotNull` which is only available since 1.4
// (when unified null checks were introduced).
&& unifiedNullChecks)
// Never generate source code in assertion exceptions in K2 to make behavior of FIR PSI & FIR light-tree equivalent
// (obtaining source code is not supported in light tree).
|| languageVersionSettings.languageVersion.usesK2
val generateSmapCopyToAnnotation: Boolean = !configuration.getBoolean(JVMConfigurationKeys.NO_SOURCE_DEBUG_EXTENSION)
val functionsWithInlineClassReturnTypesMangled: Boolean =
languageVersionSettings.supportsFeature(LanguageFeature.MangleClassMembersReturningInlineClasses)
val shouldValidateIr = configuration.getBoolean(JVMConfigurationKeys.VALIDATE_IR)
val shouldValidateBytecode = configuration.getBoolean(JVMConfigurationKeys.VALIDATE_BYTECODE)
val rootContext: CodegenContext<*> = RootContext(this)
val classFileVersion: Int = run {
val minorVersion = if (configuration.getBoolean(JVMConfigurationKeys.ENABLE_JVM_PREVIEW)) 0xffff else 0
(minorVersion shl 16) + target.majorVersion
}
val generateParametersMetadata: Boolean = configuration.getBoolean(JVMConfigurationKeys.PARAMETERS_METADATA)
val shouldInlineConstVals = languageVersionSettings.supportsFeature(LanguageFeature.InlineConstVals)
val jvmDefaultMode = languageVersionSettings.getFlag(JvmAnalysisFlags.jvmDefaultMode)
val disableOptimization = configuration.get(JVMConfigurationKeys.DISABLE_OPTIMIZATION, false)
val metadataVersion = configuration.metadataVersion()
val abiStability = configuration.get(JVMConfigurationKeys.ABI_STABILITY)
val noNewJavaAnnotationTargets = configuration.getBoolean(JVMConfigurationKeys.NO_NEW_JAVA_ANNOTATION_TARGETS)
val jvmDefaultMode: JvmDefaultMode
get() = config.jvmDefaultMode
val globalSerializationBindings = JvmSerializationBindings()
var mapInlineClass: (ClassDescriptor) -> Type = { descriptor -> typeMapper.mapType(descriptor.defaultType) }
@@ -372,8 +297,6 @@ class GenerationState private constructor(
else
null
val oldInnerClassesLogic = configuration.getBoolean(JVMConfigurationKeys.OLD_INNER_CLASSES_LOGIC)
init {
this.interceptedBuilderFactory = builderFactory
.wrapWith(
@@ -391,7 +314,7 @@ class GenerationState private constructor(
else
BuilderFactoryForDuplicateSignatureDiagnostics(
it, bindingContext, diagnostics, this.moduleName, languageVersionSettings,
useOldManglingSchemeForFunctionsWithInlineClassesInSignatures,
config.useOldManglingSchemeForFunctionsWithInlineClassesInSignatures,
shouldGenerate = { origin -> !shouldOnlyCollectSignatures(origin) },
).apply { duplicateSignatureFactory = this }
},
@@ -0,0 +1,103 @@
/*
* Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.codegen.state
import org.jetbrains.kotlin.config.*
import org.jetbrains.kotlin.metadata.deserialization.BinaryVersion
import org.jetbrains.kotlin.utils.metadataVersion
class JvmBackendConfig(configuration: CompilerConfiguration) {
val languageVersionSettings: LanguageVersionSettings = configuration.languageVersionSettings
val target: JvmTarget =
configuration.get(JVMConfigurationKeys.JVM_TARGET) ?: JvmTarget.DEFAULT
val useOldManglingSchemeForFunctionsWithInlineClassesInSignatures: Boolean =
configuration.getBoolean(JVMConfigurationKeys.USE_OLD_INLINE_CLASSES_MANGLING_SCHEME) ||
languageVersionSettings.languageVersion.run { major == 1 && minor < 4 }
val runtimeStringConcat: JvmStringConcat =
if (target.majorVersion >= JvmTarget.JVM_9.majorVersion)
configuration.get(JVMConfigurationKeys.STRING_CONCAT) ?: JvmStringConcat.INDY_WITH_CONSTANTS
else JvmStringConcat.INLINE
val samConversionsScheme: JvmClosureGenerationScheme =
configuration.get(JVMConfigurationKeys.SAM_CONVERSIONS)
?: if (languageVersionSettings.supportsFeature(LanguageFeature.SamWrapperClassesAreSynthetic))
JvmClosureGenerationScheme.INDY
else
JvmClosureGenerationScheme.CLASS
val lambdasScheme: JvmClosureGenerationScheme =
configuration.get(JVMConfigurationKeys.LAMBDAS)
?: if (languageVersionSettings.supportsFeature(LanguageFeature.LightweightLambdas))
JvmClosureGenerationScheme.INDY
else JvmClosureGenerationScheme.CLASS
val useKotlinNothingValueException: Boolean =
languageVersionSettings.apiVersion >= ApiVersion.KOTLIN_1_4 &&
!configuration.getBoolean(JVMConfigurationKeys.NO_KOTLIN_NOTHING_VALUE_EXCEPTION)
// In 1.6, `typeOf` became stable and started to rely on a few internal stdlib functions which were missing before 1.6.
val stableTypeOf: Boolean =
languageVersionSettings.apiVersion >= ApiVersion.KOTLIN_1_6
val generateOptimizedCallableReferenceSuperClasses: Boolean =
languageVersionSettings.apiVersion >= ApiVersion.KOTLIN_1_4 &&
!configuration.getBoolean(JVMConfigurationKeys.NO_OPTIMIZED_CALLABLE_REFERENCES)
val isCallAssertionsDisabled: Boolean = configuration.getBoolean(JVMConfigurationKeys.DISABLE_CALL_ASSERTIONS)
val isReceiverAssertionsDisabled: Boolean =
configuration.getBoolean(JVMConfigurationKeys.DISABLE_RECEIVER_ASSERTIONS) ||
!languageVersionSettings.supportsFeature(LanguageFeature.NullabilityAssertionOnExtensionReceiver)
val isParamAssertionsDisabled: Boolean = configuration.getBoolean(JVMConfigurationKeys.DISABLE_PARAM_ASSERTIONS)
val assertionsMode: JVMAssertionsMode = configuration.get(JVMConfigurationKeys.ASSERTIONS_MODE, JVMAssertionsMode.DEFAULT)
val isInlineDisabled: Boolean = configuration.getBoolean(CommonConfigurationKeys.DISABLE_INLINE)
val useTypeTableInSerializer: Boolean = configuration.getBoolean(JVMConfigurationKeys.USE_TYPE_TABLE)
val unifiedNullChecks: Boolean =
languageVersionSettings.apiVersion >= ApiVersion.KOTLIN_1_4 &&
!configuration.getBoolean(JVMConfigurationKeys.NO_UNIFIED_NULL_CHECKS)
val noSourceCodeInNotNullAssertionExceptions: Boolean =
(languageVersionSettings.supportsFeature(LanguageFeature.NoSourceCodeInNotNullAssertionExceptions)
// This check is needed because we generate calls to `Intrinsics.checkNotNull` which is only available since 1.4
// (when unified null checks were introduced).
&& unifiedNullChecks)
// Never generate source code in assertion exceptions in K2 to make behavior of FIR PSI & FIR light-tree equivalent
// (obtaining source code is not supported in light tree).
|| languageVersionSettings.languageVersion.usesK2
val generateSmapCopyToAnnotation: Boolean = !configuration.getBoolean(JVMConfigurationKeys.NO_SOURCE_DEBUG_EXTENSION)
val functionsWithInlineClassReturnTypesMangled: Boolean =
languageVersionSettings.supportsFeature(LanguageFeature.MangleClassMembersReturningInlineClasses)
val shouldValidateIr: Boolean = configuration.getBoolean(JVMConfigurationKeys.VALIDATE_IR)
val shouldValidateBytecode: Boolean = configuration.getBoolean(JVMConfigurationKeys.VALIDATE_BYTECODE)
val classFileVersion: Int = run {
val minorVersion = if (configuration.getBoolean(JVMConfigurationKeys.ENABLE_JVM_PREVIEW)) 0xffff else 0
(minorVersion shl 16) + target.majorVersion
}
val generateParametersMetadata: Boolean = configuration.getBoolean(JVMConfigurationKeys.PARAMETERS_METADATA)
val shouldInlineConstVals: Boolean = languageVersionSettings.supportsFeature(LanguageFeature.InlineConstVals)
val jvmDefaultMode: JvmDefaultMode = languageVersionSettings.getFlag(JvmAnalysisFlags.jvmDefaultMode)
val disableOptimization: Boolean = configuration.getBoolean(JVMConfigurationKeys.DISABLE_OPTIMIZATION)
val metadataVersion: BinaryVersion = configuration.metadataVersion()
val abiStability: JvmAbiStability? = configuration.get(JVMConfigurationKeys.ABI_STABILITY)
val noNewJavaAnnotationTargets: Boolean = configuration.getBoolean(JVMConfigurationKeys.NO_NEW_JAVA_ANNOTATION_TARGETS)
val oldInnerClassesLogic: Boolean = configuration.getBoolean(JVMConfigurationKeys.OLD_INNER_CLASSES_LOGIC)
}
@@ -46,7 +46,7 @@ public class MappingClassesForWhenByEnumCodegen {
ClassBuilder cb = state.getFactory().newVisitor(JvmDeclarationOrigin.NO_ORIGIN, mappingsClass, srcFile);
cb.defineClass(
srcFile,
state.getClassFileVersion(),
state.getConfig().getClassFileVersion(),
ACC_PUBLIC | ACC_FINAL | ACC_SUPER | ACC_SYNTHETIC,
mappingsClass.getInternalName(),
null,
@@ -60,7 +60,7 @@ public class MappingClassesForWhenByEnumCodegen {
boolean publicAbi = mappings.stream().anyMatch(WhenByEnumsMapping::isPublicAbi);
WriteAnnotationUtilKt.writeSyntheticClassMetadata(cb, state, publicAbi);
cb.done(state.getGenerateSmapCopyToAnnotation());
cb.done(state.getConfig().getGenerateSmapCopyToAnnotation());
}
private static void generateFields(@NotNull ClassBuilder cb, @NotNull List<WhenByEnumsMapping> mappings) {
@@ -34,8 +34,8 @@ private constructor(
private val shouldInlineConstVals: Boolean,
private val codegen: ExpressionCodegen?
) {
constructor(state: GenerationState) : this(state.bindingContext, state.shouldInlineConstVals, null)
constructor(codegen: ExpressionCodegen) : this(codegen.bindingContext, codegen.state.shouldInlineConstVals, codegen)
constructor(state: GenerationState) : this(state.bindingContext, state.config.shouldInlineConstVals, null)
constructor(codegen: ExpressionCodegen) : this(codegen.bindingContext, codegen.state.config.shouldInlineConstVals, codegen)
fun checkAllItemsAreConstantsSatisfying(expression: KtWhenExpression, predicate: Function1<ConstantValue<*>, Boolean>): Boolean =
expression.entries.all { entry ->
@@ -32,8 +32,8 @@ fun writeKotlinMetadata(
action: (AnnotationVisitor) -> Unit
) {
val av = cb.newAnnotation(JvmAnnotationNames.METADATA_DESC, true)
av.visit(JvmAnnotationNames.METADATA_VERSION_FIELD_NAME, state.metadataVersion.toArray())
if (!state.metadataVersion.isAtLeast(1, 5, 0)) {
av.visit(JvmAnnotationNames.METADATA_VERSION_FIELD_NAME, state.config.metadataVersion.toArray())
if (!state.config.metadataVersion.isAtLeast(1, 5, 0)) {
av.visit("bv", JvmBytecodeBinaryVersion.INSTANCE.toArray())
}
av.visit(JvmAnnotationNames.KIND_FIELD_NAME, kind.id)
@@ -77,8 +77,8 @@ class FirJvmSerializerExtension(
components: Fir2IrComponents
) : this(
session, bindings, metadata, localDelegatedProperties, approximator, components.scopeSession,
state.globalSerializationBindings, state.useTypeTableInSerializer, state.moduleName, state.classBuilderMode,
state.isParamAssertionsDisabled, state.unifiedNullChecks, state.metadataVersion, state.jvmDefaultMode,
state.globalSerializationBindings, state.config.useTypeTableInSerializer, state.moduleName, state.classBuilderMode,
state.config.isParamAssertionsDisabled, state.config.unifiedNullChecks, state.config.metadataVersion, state.jvmDefaultMode,
FirJvmElementAwareStringTable(typeMapper, components), ConstValueProviderImpl(components),
components.annotationsFromPluginRegistrar.createMetadataAnnotationsProvider()
)
@@ -86,7 +86,7 @@ class ClassCodegen private constructor(
private val innerClasses = mutableSetOf<IrClass>()
val typeMapper =
if (context.state.oldInnerClassesLogic)
if (context.config.oldInnerClassesLogic)
context.defaultTypeMapper
else object : IrTypeMapper(context) {
override fun mapType(type: IrType, mode: TypeMappingMode, sw: JvmSignatureWriter?, materialized: Boolean): Type {
@@ -118,7 +118,7 @@ class ClassCodegen private constructor(
}
defineClass(
irClass.psiElement,
state.classFileVersion,
state.config.classFileVersion,
irClass.getFlags(context.state.languageVersionSettings),
signature.name,
signature.javaGenericSignature,
@@ -151,7 +151,7 @@ class ClassCodegen private constructor(
// Generate PermittedSubclasses attribute for sealed class.
if (state.languageVersionSettings.supportsFeature(LanguageFeature.JvmPermittedSubclassesAttributeForSealed) &&
irClass.modality == Modality.SEALED &&
state.target >= JvmTarget.JVM_17
state.config.target >= JvmTarget.JVM_17
) {
generatePermittedSubclasses()
}
@@ -213,7 +213,7 @@ class ClassCodegen private constructor(
generateInnerAndOuterClasses()
visitor.done(state.generateSmapCopyToAnnotation)
visitor.done(state.config.generateSmapCopyToAnnotation)
jvmSignatureClashDetector.reportErrors()
}
@@ -281,7 +281,7 @@ class ClassCodegen private constructor(
val isMultifileClassOrPart = kind == KotlinClassHeader.Kind.MULTIFILE_CLASS || kind == KotlinClassHeader.Kind.MULTIFILE_CLASS_PART
var extraFlags = context.backendExtension.generateMetadataExtraFlags(state.abiStability)
var extraFlags = context.backendExtension.generateMetadataExtraFlags(state.config.abiStability)
if (isMultifileClassOrPart && state.languageVersionSettings.getFlag(JvmAnalysisFlags.inheritMultifileParts)) {
extraFlags = extraFlags or JvmAnnotationNames.METADATA_MULTIFILE_PARTS_INHERIT_FLAG
}
@@ -279,7 +279,7 @@ class ExpressionCodegen(
}
private fun generateNonNullAssertions() {
if (state.isParamAssertionsDisabled)
if (state.config.isParamAssertionsDisabled)
return
if ((DescriptorVisibilities.isPrivate(irFunction.visibility) && !shouldGenerateNonNullAssertionsForPrivateFun(irFunction)) ||
@@ -339,7 +339,7 @@ class ExpressionCodegen(
if (!expandedType.isNullable() && !isPrimitive(asmType)) {
mv.load(findLocalIndex(param.symbol), asmType)
mv.aconst(param.name.asString())
val methodName = if (state.unifiedNullChecks) "checkNotNullParameter" else "checkParameterIsNotNull"
val methodName = if (state.config.unifiedNullChecks) "checkNotNullParameter" else "checkParameterIsNotNull"
mv.invokestatic(JvmSymbols.INTRINSICS_CLASS_NAME, methodName, "(Ljava/lang/Object;Ljava/lang/String;)V", false)
}
}
@@ -823,7 +823,7 @@ class ExpressionCodegen(
override fun visitFieldAccess(expression: IrFieldAccessExpression, data: BlockInfo): PromisedValue {
val callee = expression.symbol.owner
if (context.state.shouldInlineConstVals) {
if (context.config.shouldInlineConstVals) {
// Const fields should only have reads, and those should have been transformed by ConstLowering.
assert(callee.constantValue() == null) { "access of const val: ${expression.dump()}" }
}
@@ -983,7 +983,7 @@ class ExpressionCodegen(
}
private fun generateGlobalReturnFlagIfPossible(expression: IrExpression, label: String) {
if (state.isInlineDisabled) {
if (state.config.isInlineDisabled) {
context.ktDiagnosticReporter.at(expression, irFunction).report(BackendErrors.NON_LOCAL_RETURN_IN_DISABLED_INLINE)
genThrow(mv, "java/lang/UnsupportedOperationException", "Non-local returns are not allowed with inlining disabled")
} else {
@@ -1476,10 +1476,10 @@ class ExpressionCodegen(
}
override fun visitStringConcatenation(expression: IrStringConcatenation, data: BlockInfo): PromisedValue {
assert(context.state.runtimeStringConcat.isDynamic) {
assert(context.config.runtimeStringConcat.isDynamic) {
"IrStringConcatenation expression should be presented only with dynamic concatenation: ${expression.dump()}"
}
val generator = StringConcatGenerator(context.state.runtimeStringConcat, mv)
val generator = StringConcatGenerator(context.config.runtimeStringConcat, mv)
expression.arguments.forEach { arg ->
if (arg is IrConst<*>) {
val type = when (arg.kind) {
@@ -1580,7 +1580,7 @@ class ExpressionCodegen(
IrInlineIntrinsicsSupport(classCodegen, element, irFunction.fileParent),
context.typeSystem,
state.languageVersionSettings,
state.unifiedNullChecks,
state.config.unifiedNullChecks,
)
return IrInlineCodegen(this, state, callee, signature, mappings, sourceCompiler, reifiedTypeInliner)
@@ -70,7 +70,7 @@ class FunctionCodegen(private val irFunction: IrFunction, private val classCodeg
)
val methodVisitor: MethodVisitor = wrapWithMaxLocalCalc(methodNode)
if (context.state.generateParametersMetadata && !isSynthetic) {
if (context.config.generateParametersMetadata && !isSynthetic) {
generateParameterNames(irFunction, methodVisitor, context.state)
}
@@ -58,7 +58,7 @@ class IrInlineIntrinsicsSupport(
when (val parent = typeParameter.owner.parent) {
is IrClass -> putClassInstance(v, parent.defaultType).also { AsmUtil.wrapJavaClassIntoKClass(v) }
is IrSimpleFunction -> {
check(classCodegen.context.state.generateOptimizedCallableReferenceSuperClasses) {
check(classCodegen.context.config.generateOptimizedCallableReferenceSuperClasses) {
"typeOf() of a non-reified type parameter is only allowed if optimized callable references are enabled.\n" +
"Please make sure API version is set to 1.4, and -Xno-optimized-callable-references is NOT used.\n" +
"Container: $parent"
@@ -33,7 +33,7 @@ object HashCode : IntrinsicMethod() {
val receiverJvmType = typeMapper.mapType(receiverIrType)
val receiverValue = receiver.accept(this, data).materialized()
val receiverType = receiverValue.type
val target = context.state.target
val target = context.config.target
when {
irFunction.origin == JvmLoweredDeclarationOrigin.INLINE_CLASS_GENERATED_IMPL_METHOD ||
irFunction.origin == JvmLoweredDeclarationOrigin.MULTI_FIELD_VALUE_CLASS_GENERATED_IMPL_METHOD ||
@@ -31,7 +31,7 @@ object IrCheckNotNull : IntrinsicMethod() {
private fun ExpressionCodegen.checkTopValueForNull() {
mv.dup()
if (state.unifiedNullChecks) {
if (state.config.unifiedNullChecks) {
mv.invokestatic(IntrinsicMethods.INTRINSICS_CLASS_NAME, "checkNotNull", "(Ljava/lang/Object;)V", false)
} else {
val ifNonNullLabel = Label()
@@ -17,7 +17,7 @@ object ThrowKotlinNothingValueException : IntrinsicMethod() {
classCodegen: ClassCodegen
): IntrinsicFunction =
IntrinsicFunction.create(expression, signature, classCodegen) { mv ->
if (classCodegen.context.state.useKotlinNothingValueException) {
if (classCodegen.context.config.useKotlinNothingValueException) {
mv.anew(Type.getObjectType("kotlin/KotlinNothingValueException"))
mv.dup()
mv.invokespecial("kotlin/KotlinNothingValueException", "<init>", "()V", false)
@@ -26,4 +26,4 @@ object ThrowKotlinNothingValueException : IntrinsicMethod() {
}
mv.athrow()
}
}
}
@@ -38,7 +38,7 @@ internal val additionalClassAnnotationPhase = makeIrFilePhase(
private class AdditionalClassAnnotationLowering(private val context: JvmBackendContext) : ClassLoweringPass {
private val symbols = context.ir.symbols.javaAnnotations
private val noNewJavaAnnotationTargets =
context.state.noNewJavaAnnotationTargets || !context.isCompilingAgainstJdk8OrLater
context.config.noNewJavaAnnotationTargets || !context.isCompilingAgainstJdk8OrLater
override fun lower(irClass: IrClass) {
if (!irClass.isAnnotationClass) return
@@ -45,7 +45,7 @@ private class AssertionLowering(private val context: JvmBackendContext) :
override fun lower(irFile: IrFile) {
// In legacy mode we treat assertions as inline function calls
if (context.state.assertionsMode != JVMAssertionsMode.LEGACY)
if (context.config.assertionsMode != JVMAssertionsMode.LEGACY)
irFile.transformChildren(this, null)
}
@@ -78,7 +78,7 @@ private class AssertionLowering(private val context: JvmBackendContext) :
if (!function.isAssert)
return super.visitCall(expression, data)
val mode = context.state.assertionsMode
val mode = context.config.assertionsMode
if (mode == JVMAssertionsMode.ALWAYS_DISABLE)
return IrCompositeImpl(expression.startOffset, expression.endOffset, context.irBuiltIns.unitType)
@@ -172,7 +172,7 @@ internal class BridgeLowering(val context: JvmBackendContext) : FileLoweringPass
return false
// We don't produce bridges for abstract functions in interfaces.
if (isJvmAbstract(context.state.jvmDefaultMode)) {
if (isJvmAbstract(context.config.jvmDefaultMode)) {
if (parentAsClass.isJvmInterface) {
// If function requires a special bridge, we should record it for generic signatures generation.
if (specialBridgeOrNull != null) {
@@ -226,7 +226,7 @@ internal class BridgeLowering(val context: JvmBackendContext) : FileLoweringPass
// If irFunction is a fake override, we replace it with a stub and redirect all calls to irFunction with calls to the stub
// instead. Otherwise, we'll end up calling the special method itself and get into an infinite loop.
bridgeTarget = when {
irFunction.isJvmAbstract(context.state.jvmDefaultMode) -> {
irFunction.isJvmAbstract(context.config.jvmDefaultMode) -> {
// If the method is abstract, then we simply generate a concrete abstract method
// to avoid generating a call to a method which does not exist in the current class.
irClass.declarations.remove(irFunction)
@@ -312,7 +312,7 @@ internal class BridgeLowering(val context: JvmBackendContext) : FileLoweringPass
}
}
}
} else if (irFunction.isJvmAbstract(context.state.jvmDefaultMode)) {
} else if (irFunction.isJvmAbstract(context.config.jvmDefaultMode)) {
// Do not generate bridge methods for abstract methods which do not override a special bridge method.
// This matches the behavior of the JVM backend, but it does mean that we generate superfluous bridges
// for abstract methods overriding a special bridge for which we do not create a bridge due to,
@@ -328,7 +328,7 @@ internal class BridgeLowering(val context: JvmBackendContext) : FileLoweringPass
if (irFunction.isFakeOverride) {
for (overriddenSymbol in irFunction.overriddenSymbols) {
val override = overriddenSymbol.owner
if (override.isJvmAbstract(context.state.jvmDefaultMode)) continue
if (override.isJvmAbstract(context.config.jvmDefaultMode)) continue
override.allOverridden()
.filter { !it.isFakeOverride }
.mapTo(blacklist) { it.jvmMethod }
@@ -69,10 +69,10 @@ internal class FunctionReferenceLowering(private val context: JvmBackendContext)
}
private val shouldGenerateIndySamConversions =
context.state.samConversionsScheme == JvmClosureGenerationScheme.INDY
context.config.samConversionsScheme == JvmClosureGenerationScheme.INDY
private val shouldGenerateIndyLambdas =
context.state.lambdasScheme == JvmClosureGenerationScheme.INDY
context.config.lambdasScheme == JvmClosureGenerationScheme.INDY
private val shouldGenerateLightweightLambdas =
shouldGenerateIndyLambdas && context.state.languageVersionSettings.supportsFeature(LanguageFeature.LightweightLambdas)
@@ -461,7 +461,7 @@ internal class FunctionReferenceLowering(private val context: JvmBackendContext)
?: throw AssertionError("Not a SAM class: ${functionSuperClass.owner.render()}")
private val useOptimizedSuperClass =
context.state.generateOptimizedCallableReferenceSuperClasses
context.config.generateOptimizedCallableReferenceSuperClasses
// This code is partially duplicated in IrUtils getAdapteeFromAdaptedForReferenceFunction
// The difference is utils version supports ReturnableBlock, but returns called function instead of call node.
@@ -56,7 +56,7 @@ private class InheritedDefaultMethodsOnClassesLowering(val context: JvmBackendCo
}
}
val implementation = declaration.findInterfaceImplementation(context.state.jvmDefaultMode)
val implementation = declaration.findInterfaceImplementation(context.config.jvmDefaultMode)
?: return declaration
return generateDelegationToDefaultImpl(implementation, declaration)
}
@@ -137,7 +137,7 @@ private class ReplaceDefaultImplsOverriddenSymbols(private val context: JvmBacke
// if the overridden symbol has been, or will be, replaced and patch it accordingly.
override fun visitSimpleFunction(declaration: IrSimpleFunction) {
declaration.overriddenSymbols = declaration.overriddenSymbols.map { symbol ->
if (symbol.owner.findInterfaceImplementation(context.state.jvmDefaultMode) != null)
if (symbol.owner.findInterfaceImplementation(context.config.jvmDefaultMode) != null)
context.cachedDeclarations.getDefaultImplsRedirection(symbol.owner).symbol
else symbol
}
@@ -164,7 +164,7 @@ private class InterfaceSuperCallsLowering(val context: JvmBackendContext) : IrEl
}
val superCallee = expression.symbol.owner
if (superCallee.isDefinitelyNotDefaultImplsMethod(context.state.jvmDefaultMode)) return super.visitCall(expression)
if (superCallee.isDefinitelyNotDefaultImplsMethod(context.config.jvmDefaultMode)) return super.visitCall(expression)
val redirectTarget = context.cachedDeclarations.getDefaultImplsFunction(superCallee)
val newCall = createDelegatingCallWithPlaceholderTypeArguments(expression, redirectTarget, context.irBuiltIns)
@@ -214,7 +214,7 @@ private class InterfaceDefaultCallsLowering(val context: JvmBackendContext) : Ir
if (!callee.hasInterfaceParent() ||
callee.origin != IrDeclarationOrigin.FUNCTION_FOR_DEFAULT_PARAMETER ||
callee.isSimpleFunctionCompiledToJvmDefault(context.state.jvmDefaultMode)
callee.isSimpleFunctionCompiledToJvmDefault(context.config.jvmDefaultMode)
) {
return super.visitCall(expression)
}
@@ -60,7 +60,7 @@ internal class InterfaceLowering(val context: JvmBackendContext) : IrElementTran
}
private fun handleInterface(irClass: IrClass) {
val jvmDefaultMode = context.state.jvmDefaultMode
val jvmDefaultMode = context.config.jvmDefaultMode
val isCompatibilityMode =
(jvmDefaultMode.isCompatibility && !irClass.hasJvmDefaultNoCompatibilityAnnotation()) ||
(jvmDefaultMode == JvmDefaultMode.ALL_INCOMPATIBLE && irClass.hasJvmDefaultWithCompatibilityAnnotation())
@@ -33,9 +33,9 @@ private enum class AssertionScope {
private class JvmArgumentNullabilityAssertionsLowering(context: JvmBackendContext) : FileLoweringPass,
IrElementTransformer<AssertionScope> {
private val isWithUnifiedNullChecks = context.state.unifiedNullChecks
private val isCallAssertionsDisabled = context.state.isCallAssertionsDisabled
private val isReceiverAssertionsDisabled = context.state.isReceiverAssertionsDisabled
private val isWithUnifiedNullChecks = context.config.unifiedNullChecks
private val isCallAssertionsDisabled = context.config.isCallAssertionsDisabled
private val isReceiverAssertionsDisabled = context.config.isReceiverAssertionsDisabled
private val specialBridgeMethods = SpecialBridgeMethods(context)
@@ -223,7 +223,7 @@ class JvmPropertiesLowering(private val backendContext: JvmBackendContext) : IrE
if (getter != null) {
val needsMangling =
getter.extensionReceiverParameter?.type?.getRequiresMangling(includeInline = true, includeMFVC = false) == true ||
(state.functionsWithInlineClassReturnTypesMangled && getter.hasMangledReturnType)
(config.functionsWithInlineClassReturnTypesMangled && getter.hasMangledReturnType)
val mangled = if (needsMangling) inlineClassReplacements.getReplacementFunction(getter) else null
defaultMethodSignatureMapper.mapFunctionName(mangled ?: getter)
} else JvmAbi.getterName(property.name.asString())
@@ -28,7 +28,7 @@ import org.jetbrains.kotlin.ir.visitors.transformChildrenVoid
internal val jvmStringConcatenationLowering = makeIrFilePhase(
{ context: JvmBackendContext ->
if (!context.state.runtimeStringConcat.isDynamic)
if (!context.config.runtimeStringConcat.isDynamic)
JvmStringConcatenationLowering(context)
else
JvmDynamicStringConcatenationLowering(context)
@@ -90,8 +90,8 @@ internal abstract class JvmValueClassAbstractLowering(
private fun IrFunction.hashSuffix(): String? = InlineClassAbi.hashSuffix(
this,
context.state.functionsWithInlineClassReturnTypesMangled,
context.state.useOldManglingSchemeForFunctionsWithInlineClassesInSignatures
context.config.functionsWithInlineClassReturnTypesMangled,
context.config.useOldManglingSchemeForFunctionsWithInlineClassesInSignatures
)
protected abstract fun transformSecondaryConstructorFlat(constructor: IrConstructor, replacement: IrSimpleFunction): List<IrDeclaration>
@@ -192,7 +192,7 @@ internal abstract class JvmValueClassAbstractLowering(
useOldMangleRules = false
)
// If the original function has signature which need mangling we still need to replace it with a mangled version.
(!function.isFakeOverride || function.findInterfaceImplementation(context.state.jvmDefaultMode) != null) && when (specificMangle) {
(!function.isFakeOverride || function.findInterfaceImplementation(context.config.jvmDefaultMode) != null) && when (specificMangle) {
SpecificMangle.Inline -> function.signatureRequiresMangling(includeInline = true, includeMFVC = false)
SpecificMangle.MultiField -> function.signatureRequiresMangling(includeInline = false, includeMFVC = true)
} -> replacement.name
@@ -224,7 +224,7 @@ internal abstract class JvmValueClassAbstractLowering(
private fun IrSimpleFunction.signatureRequiresMangling(includeInline: Boolean = true, includeMFVC: Boolean = true) =
fullValueParameterList.any { it.type.getRequiresMangling(includeInline, includeMFVC) } ||
context.state.functionsWithInlineClassReturnTypesMangled &&
context.config.functionsWithInlineClassReturnTypesMangled &&
returnType.getRequiresMangling(includeInline = includeInline, includeMFVC = false)
protected fun typedArgumentList(function: IrFunction, expression: IrMemberAccessExpression<*>) = listOfNotNull(
@@ -35,7 +35,7 @@ internal val propertyReferenceDelegationPhase = makeIrFilePhase(
private class PropertyReferenceDelegationLowering(val context: JvmBackendContext) : FileLoweringPass {
override fun lower(irFile: IrFile) {
if (!context.state.generateOptimizedCallableReferenceSuperClasses) return
if (!context.config.generateOptimizedCallableReferenceSuperClasses) return
irFile.transform(PropertyReferenceDelegationTransformer(context), null)
}
}
@@ -92,7 +92,7 @@ internal class PropertyReferenceLowering(val context: JvmBackendContext) : IrEle
context.ir.symbols.array.createType(false, listOf(makeTypeProjection(kPropertyStarType, Variance.OUT_VARIANCE)))
private val useOptimizedSuperClass =
context.state.generateOptimizedCallableReferenceSuperClasses
context.config.generateOptimizedCallableReferenceSuperClasses
private val IrClass.isSynthetic
get() = metadata !is MetadataSource.File && metadata !is MetadataSource.Class && metadata !is MetadataSource.Script
@@ -227,7 +227,7 @@ internal class PropertyReferenceLowering(val context: JvmBackendContext) : IrEle
isFinal = true
isStatic = true
visibility =
if (irClass.isInterface && context.state.jvmDefaultMode.forAllMethodsWithBody) DescriptorVisibilities.PUBLIC else JavaDescriptorVisibilities.PACKAGE_VISIBILITY
if (irClass.isInterface && context.config.jvmDefaultMode.forAllMethodsWithBody) DescriptorVisibilities.PUBLIC else JavaDescriptorVisibilities.PACKAGE_VISIBILITY
}
val localProperties = mutableListOf<IrLocalDelegatedPropertySymbol>()
@@ -31,7 +31,7 @@ internal val singletonOrConstantDelegationPhase = makeIrFilePhase(
private class SingletonOrConstantDelegationLowering(val context: JvmBackendContext) : FileLoweringPass {
override fun lower(irFile: IrFile) {
if (!context.state.generateOptimizedCallableReferenceSuperClasses) return
if (!context.config.generateOptimizedCallableReferenceSuperClasses) return
irFile.transform(SingletonOrConstantDelegationTransformer(context), null)
}
}
@@ -18,7 +18,6 @@ import org.jetbrains.kotlin.backend.jvm.JvmBackendContext
import org.jetbrains.kotlin.backend.jvm.JvmLoweredDeclarationOrigin
import org.jetbrains.kotlin.backend.jvm.ir.*
import org.jetbrains.kotlin.backend.jvm.unboxInlineClass
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.descriptors.DescriptorVisibilities
import org.jetbrains.kotlin.ir.IrElement
import org.jetbrains.kotlin.ir.IrStatement
@@ -97,7 +96,7 @@ private class TypeOperatorLowering(private val backendContext: JvmBackendContext
with(builder) {
irLetS(argument, irType = context.irBuiltIns.anyNType) { tmp ->
val message = irString("null cannot be cast to non-null type ${type.render()}")
if (backendContext.state.unifiedNullChecks) {
if (backendContext.config.unifiedNullChecks) {
// Avoid branching to improve code coverage (KT-27427).
// We have to generate a null check here, because even if argument is of non-null type,
// it can be uninitialized value, which is 'null' for reference types in JMM.
@@ -764,7 +763,7 @@ private class TypeOperatorLowering(private val backendContext: JvmBackendContext
}
private fun IrBuilderWithScope.computeNotNullAssertionText(typeOperatorCall: IrTypeOperatorCall): String? {
if (backendContext.state.noSourceCodeInNotNullAssertionExceptions) {
if (backendContext.config.noSourceCodeInNotNullAssertionExceptions) {
return when (val argument = typeOperatorCall.argument) {
is IrCall -> "${argument.symbol.owner.name.asString()}(...)"
is IrGetField -> argument.symbol.owner.name.asString()
@@ -818,7 +817,7 @@ private class TypeOperatorLowering(private val backendContext: JvmBackendContext
backendContext.ir.symbols.throwTypeCastException
private val checkExpressionValueIsNotNull: IrSimpleFunctionSymbol =
if (backendContext.state.unifiedNullChecks)
if (backendContext.config.unifiedNullChecks)
backendContext.ir.symbols.checkNotNullExpressionValue
else
backendContext.ir.symbols.checkExpressionValueIsNotNull
@@ -153,7 +153,7 @@ internal class LambdaMetafactoryArgumentsBuilder(
// In this case the corresponding method might be inaccessible in the context where it's referenced (see KT-48954).
// For now, just prohibit referencing methods from package-private Java classes through indy (without precise accessibility check).
if (implFun is IrSimpleFunction) {
val baseFun = findSuperDeclaration(implFun, false, context.state.jvmDefaultMode)
val baseFun = findSuperDeclaration(implFun, false, context.config.jvmDefaultMode)
val baseFunClass = baseFun.parent as? IrClass
if (baseFunClass != null && baseFunClass.visibility == JavaDescriptorVisibilities.PACKAGE_VISIBILITY) {
functionHazard = true
@@ -234,13 +234,13 @@ internal class LambdaMetafactoryArgumentsBuilder(
continue
val irImplFun =
if (irMemberFun.isFakeOverride)
irMemberFun.findInterfaceImplementation(context.state.jvmDefaultMode)
irMemberFun.findInterfaceImplementation(context.config.jvmDefaultMode)
?: continue
else
irMemberFun
if (irImplFun.origin == IrDeclarationOrigin.IR_EXTERNAL_JAVA_DECLARATION_STUB)
continue
if (!irImplFun.isCompiledToJvmDefault(context.state.jvmDefaultMode))
if (!irImplFun.isCompiledToJvmDefault(context.config.jvmDefaultMode))
return true
}
return false
@@ -10,6 +10,6 @@ import org.jetbrains.kotlin.backend.jvm.JvmBackendContext
import org.jetbrains.kotlin.ir.declarations.IrModuleFragment
fun validateIr(context: JvmBackendContext, module: IrModuleFragment) {
if (!context.state.shouldValidateIr) return
if (!context.config.shouldValidateIr) return
validationCallback(context, module, checkProperties = true)
}
}
@@ -21,6 +21,7 @@ import org.jetbrains.kotlin.backend.jvm.mapping.IrTypeMapper
import org.jetbrains.kotlin.backend.jvm.mapping.MethodSignatureMapper
import org.jetbrains.kotlin.codegen.inline.SMAP
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.codegen.state.JvmBackendConfig
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor
import org.jetbrains.kotlin.ir.IrBuiltIns
@@ -80,6 +81,8 @@ class JvmBackendContext(
val newParameterToCaptured: Map<IrValueParameter, IrValueSymbol>,
)
val config: JvmBackendConfig = state.config
// If not-null, this is populated by LocalDeclarationsLowering with the intermediate data
// allowing mapping from local function captures to parameters and accurate transformation
// of calls to local functions from code fragments (i.e. the expression evaluator).
@@ -176,7 +179,7 @@ class JvmBackendContext(
val staticDefaultStubs = ConcurrentHashMap<IrSimpleFunctionSymbol, IrSimpleFunction>()
val inlineClassReplacements = MemoizedInlineClassReplacements(state.functionsWithInlineClassReturnTypesMangled, irFactory, this)
val inlineClassReplacements = MemoizedInlineClassReplacements(config.functionsWithInlineClassReturnTypesMangled, irFactory, this)
val multiFieldValueClassReplacements = MemoizedMultiFieldValueClassReplacements(irFactory, this)
@@ -74,7 +74,7 @@ class JvmSymbols(
// (they are expected to be provided at run-time by the corresponding bootstrap method).
val kotlinJvmInternalInvokeDynamicPackage: IrPackageFragment = createPackage(FqName("kotlin.jvm.internal.invokeDynamic"))
private val generateOptimizedCallableReferenceSuperClasses = context.state.generateOptimizedCallableReferenceSuperClasses
private val generateOptimizedCallableReferenceSuperClasses = context.config.generateOptimizedCallableReferenceSuperClasses
private fun createPackage(fqName: FqName): IrPackageFragment =
IrExternalPackageFragmentImpl.createEmptyExternalPackageFragment(context.state.module, fqName)
@@ -220,7 +220,7 @@ class MemoizedInlineClassReplacements(
noFakeOverride: Boolean = false,
body: IrFunction.() -> Unit
): IrSimpleFunction {
val useOldManglingScheme = context.state.useOldManglingSchemeForFunctionsWithInlineClassesInSignatures
val useOldManglingScheme = context.config.useOldManglingSchemeForFunctionsWithInlineClassesInSignatures
val replacement = buildReplacementInner(function, replacementOrigin, noFakeOverride, useOldManglingScheme, body)
// When using the new mangling scheme we might run into dependencies using the old scheme
// for which we will fall back to the old mangling scheme as well.
@@ -282,7 +282,7 @@ class MemoizedMultiFieldValueClassReplacements(
&& function.fullValueParameterList.any { it.type.needsMfvcFlattening() }
&& run {
if (!function.isFakeOverride) return@run true
val superDeclaration = findSuperDeclaration(function, false, context.state.jvmDefaultMode)
val superDeclaration = findSuperDeclaration(function, false, context.config.jvmDefaultMode)
getReplacementFunction(superDeclaration) != null
} -> createMethodReplacement(function)
@@ -53,7 +53,7 @@ abstract class MemoizedValueClassAbstractReplacements(
// It is a JVM default interface method if one of the following conditions are true:
// - it is a Java method,
// - it is a Kotlin function compiled to JVM default interface method.
return overridden.isFromJava() || overridden.isCompiledToJvmDefault(context.state.jvmDefaultMode)
return overridden.isFromJava() || overridden.isCompiledToJvmDefault(context.config.jvmDefaultMode)
}
protected abstract fun createStaticReplacement(function: IrFunction): IrSimpleFunction
@@ -67,7 +67,7 @@ fun IrStatement.unwrapInlineLambda(): IrFunctionReference? = when (this) {
}
fun IrFunction.isInlineFunctionCall(context: JvmBackendContext): Boolean =
(!context.state.isInlineDisabled || typeParameters.any { it.isReified }) && (isInline || isInlineArrayConstructor(context.irBuiltIns))
(!context.config.isInlineDisabled || typeParameters.any { it.isReified }) && (isInline || isInlineArrayConstructor(context.irBuiltIns))
fun IrDeclaration.isInlineOnly(): Boolean =
this is IrFunction && (
@@ -444,7 +444,7 @@ class MethodSignatureMapper(private val context: JvmBackendContext, private val
mapAsmMethod(findSuperDeclaration(function, isSuperCall))
private fun findSuperDeclaration(function: IrSimpleFunction, isSuperCall: Boolean): IrSimpleFunction =
findSuperDeclaration(function, isSuperCall, context.state.jvmDefaultMode)
findSuperDeclaration(function, isSuperCall, context.config.jvmDefaultMode)
private fun getJvmMethodNameIfSpecial(irFunction: IrSimpleFunction): String? {
if (
@@ -522,7 +522,7 @@ class MethodSignatureMapper(private val context: JvmBackendContext, private val
is IrConstructor ->
irFun
is IrSimpleFunction ->
findSuperDeclaration(irFun, false, context.state.jvmDefaultMode)
findSuperDeclaration(irFun, false, context.config.jvmDefaultMode)
else ->
throw AssertionError("Simple function or constructor expected: ${irFun.render()}")
}
@@ -59,7 +59,7 @@ class DescriptorMetadataSerializer(
context.state.bindingTrace.record(
CodegenBinding.DELEGATED_PROPERTIES_WITH_METADATA,
// key for local delegated properties metadata in interfaces depends on jvmDefaultMode
if (irClass.isInterface && !context.state.jvmDefaultMode.forAllMethodsWithBody) context.defaultTypeMapper.mapClass(
if (irClass.isInterface && !context.config.jvmDefaultMode.forAllMethodsWithBody) context.defaultTypeMapper.mapClass(
context.cachedDeclarations.getDefaultImplsClass(
irClass
)
@@ -316,7 +316,7 @@ open class ParcelableCodegenExtension : ParcelableExtensionBase, ExpressionCodeg
writeNewArrayMethod(codegenForCreator, parcelableClass, parcelableCreatorClassType, creatorClass, parcelerObject)
writeCreateFromParcel(codegenForCreator, parcelableClass, parcelableCreatorClassType, creatorClass, parcelClassType, parcelAsmType, parcelerObject, properties)
classBuilderForCreator.done(codegen.state.generateSmapCopyToAnnotation)
classBuilderForCreator.done(codegen.state.config.generateSmapCopyToAnnotation)
}
private fun writeCreatorConstructor(codegen: ImplementationBodyCodegen, creatorClass: ClassDescriptor, creatorAsmType: Type) {
@@ -658,7 +658,7 @@ internal fun createSingletonLambda(
)
lambdaCodegen.v.defineClass(
null,
outerClassCodegen.state.classFileVersion,
outerClassCodegen.state.config.classFileVersion,
Opcodes.ACC_FINAL or Opcodes.ACC_SUPER or Opcodes.ACC_SYNTHETIC,
lambdaType.internalName,
"L${jvmLambdaType.internalName};L${function0Type.internalName}<L${kSerializerType.internalName}<*>;>;",
@@ -773,7 +773,7 @@ internal fun createSingletonLambda(
}
writeSyntheticClassMetadata(lambdaClassBuilder, lambdaCodegen.state, false)
lambdaClassBuilder.done(lambdaCodegen.state.generateSmapCopyToAnnotation)
lambdaClassBuilder.done(lambdaCodegen.state.config.generateSmapCopyToAnnotation)
return lambdaType
}