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 Codegen: Emit lookupswitch/tableswitch for when-expressions over Char if possible #5305

Open
wants to merge 1 commit 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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,15 @@ class SwitchGenerator(private val expression: IrWhen, private val data: BlockInf
cases
)
}
subject is IrGetValue && areConstCharComparisons(conditions) -> {
val cases = extractSwitchCasesAndFilterUnreachableLabels(callToLabels, expressionToLabels)
IntSwitch(
subject,
elseExpression,
expressionToLabels,
cases.map { ValueToLabel((it.value as Char).code, it.label) }
)
}
areConstStringComparisons(conditions) -> {
val cases = extractSwitchCasesAndFilterUnreachableLabels(callToLabels, expressionToLabels)
StringSwitch(
Expand Down Expand Up @@ -193,6 +202,10 @@ class SwitchGenerator(private val expression: IrWhen, private val data: BlockInf
return checkTypeSpecifics(conditions, { it.isInt() }, { it.kind == IrConstKind.Int })
}

private fun areConstCharComparisons(conditions: List<IrCall>): Boolean {
return checkTypeSpecifics(conditions, { it.isChar() }, { it.kind == IrConstKind.Char })
}

private fun areConstStringComparisons(conditions: List<IrCall>): Boolean {
return checkTypeSpecifics(
conditions,
Expand Down
11 changes: 10 additions & 1 deletion compiler/testData/codegen/bytecodeText/when/lookupSwitch.kt
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,14 @@ fun foo(x: Int): String {
}
}

// 1 LOOKUPSWITCH
fun foo(p: Char): String {
return when (p) {
'a' -> "a"
'g' -> "g"
'h' -> "h"
else -> "else"
}
}

// 2 LOOKUPSWITCH
// 0 TABLESWITCH
16 changes: 15 additions & 1 deletion compiler/testData/codegen/bytecodeText/when/tableSwitch.kt
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,19 @@ fun foo(x: Int): String {
}
}

fun foo(p: Char): String {
return when (p) {
'a' -> "a"
'b' -> "b"
'c' -> "c"
'd' -> "d"
'e' -> "e"
'f' -> "f"
'g' -> "g"
'h' -> "h"
else -> "else"
}
}

// 0 LOOKUPSWITCH
// 1 TABLESWITCH
// 2 TABLESWITCH