KT-53465, KT-53677 Get rid of unnecessary checkcasts to array of reified type

This commit is contained in:
Pavel Mikhailovskii
2022-09-06 11:12:42 +02:00
committed by teamcity
parent d8522a8967
commit a75d5ba4cf
17 changed files with 213 additions and 1 deletions
@@ -19,6 +19,7 @@ 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.descriptors.DescriptorVisibilities
import org.jetbrains.kotlin.ir.IrBuiltIns
import org.jetbrains.kotlin.ir.IrElement
import org.jetbrains.kotlin.ir.IrStatement
import org.jetbrains.kotlin.ir.UNDEFINED_OFFSET
@@ -36,6 +37,9 @@ import org.jetbrains.kotlin.ir.visitors.IrElementVisitorVoid
import org.jetbrains.kotlin.ir.visitors.acceptChildrenVoid
import org.jetbrains.kotlin.ir.visitors.acceptVoid
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.types.Variance
import org.jetbrains.kotlin.types.checker.SimpleClassicTypeSystemContext.getArgument
import org.jetbrains.kotlin.types.checker.SimpleClassicTypeSystemContext.isTypeVariableType
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import org.jetbrains.org.objectweb.asm.Handle
import org.jetbrains.org.objectweb.asm.Opcodes
@@ -88,6 +92,8 @@ private class TypeOperatorLowering(private val backendContext: JvmBackendContext
builder.irAs(argument, type)
argument.type.isInlineClassType() && argument.type.isSubtypeOfClass(type.erasedUpperBound.symbol) ->
argument
isCompatibleArrayType(argument.type, type) ->
argument
type.isNullable() || argument.isDefinitelyNotNull() ->
builder.irAs(argument, type)
else -> {
@@ -121,6 +127,22 @@ private class TypeOperatorLowering(private val backendContext: JvmBackendContext
}
}
private fun isCompatibleArrayType(actualType: IrType, expectedType: IrType): Boolean {
var actual = actualType
var expected = expectedType
while ((actual.isArray() || actual.isNullableArray()) && (expected.isArray() || expected.isNullableArray())) {
actual = actual.getArrayElementLowerType()
expected = expected.getArrayElementLowerType()
}
if (actual == actualType || expected == expectedType) return false
return actual.isSubtypeOfClass(expected.erasedUpperBound.symbol)
}
private fun IrType.getArrayElementLowerType(): IrType =
if (isBoxedArray && this is IrSimpleType && (arguments.singleOrNull() as? IrTypeProjection)?.variance == Variance.IN_VARIANCE)
backendContext.irBuiltIns.anyNType
else getArrayElementType(backendContext.irBuiltIns)
// TODO extract null check elimination on IR somewhere?
private fun IrExpression.isDefinitelyNotNull(): Boolean =
when (this) {