backend: Process 'until MIN_VALUE' in for loops
This patch takes into account a corner case available for loops
over a progression (see backend.native/tests/external/codegen/box/
ranges/forInUntil/forInUntilMinint.kt test):
for (i in 0 until Int.MIN_VALUE) { ... }
Here we cannot use subtraction to obtain a right bound of the loop
due to an overflow. Instead we consider any loop with MIN_VALUE in
it's right bound as empty loop. Such behaviour is similar to the one
of 'until' method.
So now the empty check for a loops with 'until' call:
for (i in first until bound) { ... }
is as follows:
val last = getProgressionLast(first, bound, step) // Only if step==1
if (first <= last && bound > <Int|Long|Char>.MIN_VALUE) {
do { ... } while(i != last)
}
Further improvements: We can generate a simpler IR for some simple
frequent cases (e.g. for until calls without steps) and eliminate
loops if we can prove that they are empty.
This commit is contained in:
@@ -0,0 +1,10 @@
|
||||
fun f1(): Int { print("1"); return 0 }
|
||||
fun f2(): Int { print("2"); return 6 }
|
||||
fun f3(): Int { print("3"); return 2 }
|
||||
fun f4(): Int { print("4"); return 3 }
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
for (i in f1()..f2() step f3() step f4()) { }; println()
|
||||
for (i in f1() until f2() step f3() step f4()) {}; println()
|
||||
for (i in f2() downTo f1() step f3() step f4()) {}; println()
|
||||
}
|
||||
@@ -3,6 +3,20 @@ fun main(args: Array<String>) {
|
||||
for (i in Int.MAX_VALUE - 1 until Int.MAX_VALUE) { print(i); print(' ') }; println()
|
||||
for (i in Int.MIN_VALUE + 1 downTo Int.MIN_VALUE) { print(i); print(' ') }; println()
|
||||
|
||||
// Empty loops
|
||||
for (i in Byte.MIN_VALUE until Byte.MIN_VALUE) { print(i); print(' ') }
|
||||
for (i in Short.MIN_VALUE until Short.MIN_VALUE) { print(i); print(' ') }
|
||||
for (i in Int.MIN_VALUE until Int.MIN_VALUE) { print(i); print(' ') }
|
||||
for (i in Long.MIN_VALUE until Long.MIN_VALUE) { print(i); print(' ') }
|
||||
for (i in 0.toChar() until 0.toChar()) { print(i); print(' ') }
|
||||
|
||||
for (i in 0 until Byte.MIN_VALUE) { print(i); print(' ') }
|
||||
for (i in 0 until Short.MIN_VALUE) { print(i); print(' ') }
|
||||
for (i in 0 until Int.MIN_VALUE) { print(i); print(' ') }
|
||||
for (i in 0 until Long.MIN_VALUE) { print(i); print(' ') }
|
||||
for (i in 'a' until 0.toChar()) { print(i); print(' ') }
|
||||
|
||||
|
||||
val M = Int.MAX_VALUE / 2
|
||||
for (i in M + 4..M + 10 step M) { print(i); print(' ') }; println()
|
||||
}
|
||||
Reference in New Issue
Block a user