-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Fix #502: Optimize Array.apply([...])
to [...]
#6821
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
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
276c8f8
Fix #502: Optimize `Array.apply([...])` to `[...]`
nicolasstucki 772f5b9
Factor out test code
nicolasstucki f3beaa8
Optimize Array.apply only when ClassTag is statically known
nicolasstucki 73a8c83
Only strip the type ascription
nicolasstucki 7db8083
Add some documentation
nicolasstucki 4cdbcda
Use ScalaBoxedClasses
nicolasstucki 1541817
Fix documentation
nicolasstucki File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
package dotty.tools.dotc | ||
package transform | ||
|
||
import core._ | ||
import MegaPhase._ | ||
import Contexts.Context | ||
import Symbols._ | ||
import Types._ | ||
import StdNames._ | ||
import ast.Trees._ | ||
import dotty.tools.dotc.ast.tpd | ||
|
||
import scala.reflect.ClassTag | ||
|
||
|
||
/** This phase rewrites calls to `Array.apply` to a direct instantiation of the array in the bytecode. | ||
* | ||
* Transforms `scala.Array.apply([....])` and `scala.Array.apply(..., [....])` into `[...]` | ||
*/ | ||
class ArrayApply extends MiniPhase { | ||
import tpd._ | ||
|
||
override def phaseName: String = "arrayApply" | ||
|
||
override def transformApply(tree: tpd.Apply)(implicit ctx: Context): tpd.Tree = { | ||
if (tree.symbol.name == nme.apply && tree.symbol.owner == defn.ArrayModule) { // Is `Array.apply` | ||
tree.args match { | ||
case StripAscription(Apply(wrapRefArrayMeth, (seqLit: tpd.JavaSeqLiteral) :: Nil)) :: ct :: Nil | ||
if defn.WrapArrayMethods().contains(wrapRefArrayMeth.symbol) && elideClassTag(ct) => | ||
seqLit | ||
|
||
case elem0 :: StripAscription(Apply(wrapRefArrayMeth, (seqLit: tpd.JavaSeqLiteral) :: Nil)) :: Nil | ||
if defn.WrapArrayMethods().contains(wrapRefArrayMeth.symbol) => | ||
tpd.JavaSeqLiteral(elem0 :: seqLit.elems, seqLit.elemtpt) | ||
|
||
case _ => | ||
tree | ||
} | ||
|
||
} else tree | ||
} | ||
|
||
/** Only optimize when classtag if it is one of | ||
* - `ClassTag.apply(classOf[XYZ])` | ||
* - `ClassTag.apply(java.lang.XYZ.Type)` for boxed primitives `XYZ`` | ||
* - `ClassTag.XYZ` for primitive types | ||
*/ | ||
private def elideClassTag(ct: Tree)(implicit ctx: Context): Boolean = ct match { | ||
case Apply(_, rc :: Nil) if ct.symbol == defn.ClassTagModule_apply => | ||
rc match { | ||
case _: Literal => true // ClassTag.apply(classOf[XYZ]) | ||
case rc: RefTree if rc.name == nme.TYPE_ => | ||
// ClassTag.apply(java.lang.XYZ.Type) | ||
defn.ScalaBoxedClasses().contains(rc.symbol.maybeOwner.companionClass) | ||
case _ => false | ||
} | ||
case Apply(ctm: RefTree, _) if ctm.symbol.maybeOwner.companionModule == defn.ClassTagModule => | ||
// ClassTag.XYZ | ||
nme.ScalaValueNames.contains(ctm.name) | ||
case _ => false | ||
} | ||
|
||
object StripAscription { | ||
def unapply(tree: Tree)(implicit ctx: Context): Some[Tree] = tree match { | ||
case Typed(expr, _) => unapply(expr) | ||
case _ => Some(tree) | ||
} | ||
} | ||
} |
109 changes: 109 additions & 0 deletions
109
compiler/test/dotty/tools/backend/jvm/ArrayApplyOptTest.scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,109 @@ | ||
package dotty.tools.backend.jvm | ||
|
||
import org.junit.Test | ||
import org.junit.Assert._ | ||
|
||
import scala.tools.asm.Opcodes._ | ||
|
||
class ArrayApplyOptTest extends DottyBytecodeTest { | ||
import ASMConverters._ | ||
|
||
@Test def testArrayEmptyGenericApply= { | ||
test("Array[String]()", List(Op(ICONST_0), TypeOp(ANEWARRAY, "java/lang/String"), Op(POP), Op(RETURN))) | ||
test("Array[Unit]()", List(Op(ICONST_0), TypeOp(ANEWARRAY, "scala/runtime/BoxedUnit"), Op(POP), Op(RETURN))) | ||
test("Array[Object]()", List(Op(ICONST_0), TypeOp(ANEWARRAY, "java/lang/Object"), Op(POP), Op(RETURN))) | ||
test("Array[Boolean]()", newArray0Opcodes(T_BOOLEAN)) | ||
test("Array[Byte]()", newArray0Opcodes(T_BYTE)) | ||
test("Array[Short]()", newArray0Opcodes(T_SHORT)) | ||
test("Array[Int]()", newArray0Opcodes(T_INT)) | ||
test("Array[Long]()", newArray0Opcodes(T_LONG)) | ||
test("Array[Float]()", newArray0Opcodes(T_FLOAT)) | ||
test("Array[Double]()", newArray0Opcodes(T_DOUBLE)) | ||
test("Array[Char]()", newArray0Opcodes(T_CHAR)) | ||
test("Array[T]()", newArray0Opcodes(T_INT)) | ||
} | ||
|
||
@Test def testArrayGenericApply= { | ||
def opCodes(tpe: String) = | ||
List(Op(ICONST_2), TypeOp(ANEWARRAY, tpe), Op(DUP), Op(ICONST_0), Ldc(LDC, "a"), Op(AASTORE), Op(DUP), Op(ICONST_1), Ldc(LDC, "b"), Op(AASTORE), Op(POP), Op(RETURN)) | ||
test("""Array("a", "b")""", opCodes("java/lang/String")) | ||
test("""Array[Object]("a", "b")""", opCodes("java/lang/Object")) | ||
} | ||
|
||
@Test def testArrayApplyBoolean = | ||
test("Array(true, false)", newArray2Opcodes(T_BOOLEAN, List(Op(DUP), Op(ICONST_0), Op(ICONST_1), Op(BASTORE), Op(DUP), Op(ICONST_1), Op(ICONST_0), Op(BASTORE)))) | ||
|
||
@Test def testArrayApplyByte = | ||
test("Array[Byte](1, 2)", newArray2Opcodes(T_BYTE, List(Op(DUP), Op(ICONST_0), Op(ICONST_1), Op(BASTORE), Op(DUP), Op(ICONST_1), Op(ICONST_2), Op(BASTORE)))) | ||
|
||
@Test def testArrayApplyShort = | ||
test("Array[Short](1, 2)", newArray2Opcodes(T_SHORT, List(Op(DUP), Op(ICONST_0), Op(ICONST_1), Op(SASTORE), Op(DUP), Op(ICONST_1), Op(ICONST_2), Op(SASTORE)))) | ||
|
||
@Test def testArrayApplyInt = { | ||
test("Array(1, 2)", newArray2Opcodes(T_INT, List(Op(DUP), Op(ICONST_0), Op(ICONST_1), Op(IASTORE), Op(DUP), Op(ICONST_1), Op(ICONST_2), Op(IASTORE)))) | ||
test("""Array[T](t, t)""", newArray2Opcodes(T_INT, List(Op(DUP), Op(ICONST_0), Field(GETSTATIC, "Foo$", "MODULE$", "LFoo$;"), Invoke(INVOKEVIRTUAL, "Foo$", "t", "()I", false), Op(IASTORE), Op(DUP), Op(ICONST_1), Field(GETSTATIC, "Foo$", "MODULE$", "LFoo$;"), Invoke(INVOKEVIRTUAL, "Foo$", "t", "()I", false), Op(IASTORE)))) | ||
} | ||
|
||
@Test def testArrayApplyLong = | ||
test("Array(2L, 3L)", newArray2Opcodes(T_LONG, List(Op(DUP), Op(ICONST_0), Ldc(LDC, 2), Op(LASTORE), Op(DUP), Op(ICONST_1), Ldc(LDC, 3), Op(LASTORE)))) | ||
|
||
@Test def testArrayApplyFloat = | ||
test("Array(2.1f, 3.1f)", newArray2Opcodes(T_FLOAT, List(Op(DUP), Op(ICONST_0), Ldc(LDC, 2.1f), Op(FASTORE), Op(DUP), Op(ICONST_1), Ldc(LDC, 3.1f), Op(FASTORE)))) | ||
|
||
@Test def testArrayApplyDouble = | ||
test("Array(2.2d, 3.2d)", newArray2Opcodes(T_DOUBLE, List(Op(DUP), Op(ICONST_0), Ldc(LDC, 2.2d), Op(DASTORE), Op(DUP), Op(ICONST_1), Ldc(LDC, 3.2d), Op(DASTORE)))) | ||
|
||
@Test def testArrayApplyChar = | ||
test("Array('x', 'y')", newArray2Opcodes(T_CHAR, List(Op(DUP), Op(ICONST_0), IntOp(BIPUSH, 120), Op(CASTORE), Op(DUP), Op(ICONST_1), IntOp(BIPUSH, 121), Op(CASTORE)))) | ||
|
||
@Test def testArrayApplyUnit = | ||
test("Array[Unit]((), ())", List(Op(ICONST_2), TypeOp(ANEWARRAY, "scala/runtime/BoxedUnit"), Op(DUP), | ||
Op(ICONST_0), Field(GETSTATIC, "scala/runtime/BoxedUnit", "UNIT", "Lscala/runtime/BoxedUnit;"), Op(AASTORE), Op(DUP), | ||
Op(ICONST_1), Field(GETSTATIC, "scala/runtime/BoxedUnit", "UNIT", "Lscala/runtime/BoxedUnit;"), Op(AASTORE), Op(POP), Op(RETURN))) | ||
|
||
@Test def testArrayInlined = test( | ||
"""{ | ||
| inline def array(xs: =>Int*): Array[Int] = Array(xs: _*) | ||
| array(1, 2) | ||
|}""".stripMargin, | ||
newArray2Opcodes(T_INT, List(Op(DUP), Op(ICONST_0), Op(ICONST_1), Op(IASTORE), Op(DUP), Op(ICONST_1), Op(ICONST_2), Op(IASTORE), TypeOp(CHECKCAST, "[I"))) | ||
) | ||
|
||
@Test def testArrayInlined2 = test( | ||
"""{ | ||
| inline def array(x: =>Int, xs: =>Int*): Array[Int] = Array(x, xs: _*) | ||
| array(1, 2) | ||
|}""".stripMargin, | ||
newArray2Opcodes(T_INT, List(Op(DUP), Op(ICONST_0), Op(ICONST_1), Op(IASTORE), Op(DUP), Op(ICONST_1), Op(ICONST_2), Op(IASTORE))) | ||
) | ||
|
||
private def newArray0Opcodes(tpe: Int, init: List[Any] = Nil): List[Any] = | ||
Op(ICONST_0) :: IntOp(NEWARRAY, tpe) :: init ::: Op(POP) :: Op(RETURN) :: Nil | ||
|
||
private def newArray2Opcodes(tpe: Int, init: List[Any] = Nil): List[Any] = | ||
Op(ICONST_2) :: IntOp(NEWARRAY, tpe) :: init ::: Op(POP) :: Op(RETURN) :: Nil | ||
|
||
private def test(code: String, expectedInstructions: List[Any])= { | ||
val source = | ||
s"""class Foo { | ||
| import Foo._ | ||
| def test: Unit = $code | ||
|} | ||
|object Foo { | ||
| opaque type T = Int | ||
| def t: T = 1 | ||
|} | ||
""".stripMargin | ||
|
||
checkBCode(source) { dir => | ||
val clsIn = dir.lookupName("Foo.class", directory = false).input | ||
val clsNode = loadClassNode(clsIn) | ||
val meth = getMethod(clsNode, "test") | ||
|
||
val instructions = instructionsFromMethod(meth) | ||
|
||
assertEquals(expectedInstructions, instructions) | ||
} | ||
} | ||
|
||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
Ok | ||
foo | ||
bar |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
import scala.reflect.ClassTag | ||
|
||
object Test extends App { | ||
Array[Int](1, 2) | ||
|
||
try { | ||
Array[Int](1, 2)(null) | ||
??? | ||
} catch { | ||
case _: NullPointerException => println("Ok") | ||
} | ||
|
||
Array[Int](1, 2)({println("foo"); the[ClassTag[Int]]}) | ||
|
||
Array[Int](1, 2)(ClassTag.apply({ println("bar"); classOf[Int]})) | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
object Test extends App { | ||
val a = Array("1") | ||
val a2 = Array(a: _*) | ||
a2(0) = "2" | ||
assert(a(0) == "1") | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.