summaryrefslogtreecommitdiff
path: root/src/compiler/scala/tools/nsc/backend/opt/ClosureElimination.scala
blob: a866173a88497bbd364f6f567257395bb2127fc7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
 /* NSC -- new Scala compiler
 * Copyright 2005-2013 LAMP/EPFL
 * @author  Iulian Dragos
 */

package scala.tools.nsc
package backend.opt

import scala.tools.nsc.backend.icode.analysis.LubException

/**
 *  @author Iulian Dragos
 */
abstract class ClosureElimination extends SubComponent {
  import global._
  import icodes._
  import icodes.opcodes._

  val phaseName = "closelim"

  override val enabled: Boolean = settings.Xcloselim

  /** Create a new phase */
  override def newPhase(p: Phase) = new ClosureEliminationPhase(p)

  /** A simple peephole optimizer. */
  val peephole = new PeepholeOpt {

    def peep(bb: BasicBlock, i1: Instruction, i2: Instruction) = (i1, i2) match {
      case (CONSTANT(c), DROP(_)) =>
        if (c.tag == UnitTag) Some(List(i2)) else Some(Nil)

      case (LOAD_LOCAL(x), STORE_LOCAL(y)) =>
        if (x eq y) Some(Nil) else None

      case (STORE_LOCAL(x), LOAD_LOCAL(y)) if (x == y) =>
        var liveOut = liveness.out(bb)
        if (!liveOut(x)) {
          debuglog("store/load to a dead local? " + x)
          val instrs = bb.getArray
          var idx = instrs.length - 1
          while (idx > 0 && (instrs(idx) ne i2)) {
            liveOut = liveness.interpret(liveOut, instrs(idx))
            idx -= 1
          }
          if (!liveOut(x)) {
            log("Removing dead store/load of " + x.sym.initialize.defString)
            Some(Nil)
          } else None
        } else
          Some(List(DUP(x.kind), STORE_LOCAL(x)))

      case (LOAD_LOCAL(_), DROP(_)) | (DUP(_), DROP(_)) =>
        Some(Nil)

      case (BOX(t1), UNBOX(t2)) if (t1 == t2) =>
        Some(Nil)

      case (LOAD_FIELD(sym, /* isStatic */false), DROP(_)) if !sym.hasAnnotation(definitions.VolatileAttr) && inliner.isClosureClass(sym.owner) =>
        Some(DROP(REFERENCE(definitions.ObjectClass)) :: Nil)

      case _ => None
    }
  }

  /** The closure elimination phase.
   */
  class ClosureEliminationPhase(prev: Phase) extends ICodePhase(prev) {

    def name = phaseName
    val closser = new ClosureElim

    override def apply(c: IClass): Unit = {
      if (closser ne null)
        closser analyzeClass c
    }
  }

  /**
   * Remove references to the environment through fields of a closure object.
   * This has to be run after an 'apply' method has been inlined, but it still
   * references the closure object.
   *
   */
  class ClosureElim {
    def analyzeClass(cls: IClass): Unit = if (settings.Xcloselim) {
      log(s"Analyzing ${cls.methods.size} methods in $cls.")
      cls.methods foreach { m =>
        analyzeMethod(m)
        peephole(m)
     }}

    val cpp = new copyPropagation.CopyAnalysis

    import copyPropagation._

    /* Some embryonic copy propagation. */
    def analyzeMethod(m: IMethod): Unit = try {if (m.hasCode) {
      cpp.init(m)
      cpp.run()

      m.linearizedBlocks() foreach { bb =>
        var info = cpp.in(bb)
        debuglog("Cpp info at entry to block " + bb + ": " + info)

        for (i <- bb) {
          i match {
            case LOAD_LOCAL(l) if info.bindings isDefinedAt LocalVar(l) =>
              val t = info.getBinding(l)
              t match {
              	case Deref(This) | Const(_) =>
                  bb.replaceInstruction(i, valueToInstruction(t))
                  debuglog(s"replaced $i with $t")

                case _ =>
                  val t = info.getAlias(l)
                  bb.replaceInstruction(i, LOAD_LOCAL(t))
                  debuglog(s"replaced $i with $t")
              }

            case LOAD_FIELD(f, false) /* if accessible(f, m.symbol) */ =>
              def replaceFieldAccess(r: Record) {
                val Record(cls, _) = r
                info.getFieldNonRecordValue(r, f) foreach { v =>
                        bb.replaceInstruction(i, DROP(REFERENCE(cls)) :: valueToInstruction(v) :: Nil)
                        debuglog(s"replaced $i with $v")
                }
              }

              info.stack(0) match {
                case r @ Record(_, bindings) if bindings isDefinedAt f =>
                  replaceFieldAccess(r)

                case Deref(LocalVar(l)) =>
                  info.getBinding(l) match {
                    case r @ Record(_, bindings) if bindings isDefinedAt f =>
                      replaceFieldAccess(r)
                    case _ =>
                  }
                case Deref(Field(r1, f1)) =>
                  info.getFieldValue(r1, f1) match {
                    case Some(r @ Record(_, bindings)) if bindings isDefinedAt f =>
                      replaceFieldAccess(r)
                    case _ =>
                  }

                case _ =>
              }

            case UNBOX(boxType) =>
              info.stack match {
                case Deref(LocalVar(loc1)) :: _ if info.bindings isDefinedAt LocalVar(loc1) =>
                  val value = info.getBinding(loc1)
                  value match {
                    case Boxed(LocalVar(loc2)) if loc2.kind == boxType =>
                      bb.replaceInstruction(i, DROP(icodes.ObjectReference) :: valueToInstruction(info.getBinding(loc2)) :: Nil)
                      debuglog("replaced " + i + " with " + info.getBinding(loc2))
                    case _ =>
                      ()
                  }
                case Boxed(LocalVar(loc1)) :: _ if loc1.kind == boxType =>
                  val loc2 = info.getAlias(loc1)
                  bb.replaceInstruction(i, DROP(icodes.ObjectReference) :: valueToInstruction(Deref(LocalVar(loc2))) :: Nil)
                  debuglog("replaced " + i + " with " + LocalVar(loc2))
                case _ =>
              }

            case _ =>
          }
          info = cpp.interpret(info, i)
        }
      }
    }} catch {
      case e: LubException =>
        Console.println("In method: " + m)
        Console.println(e)
        e.printStackTrace
    }

    /* Partial mapping from values to instructions that load them. */
    def valueToInstruction(v: Value): Instruction = (v: @unchecked) match {
      case Deref(LocalVar(v)) =>
        LOAD_LOCAL(v)
      case Const(k) =>
        CONSTANT(k)
      case Deref(This) =>
        THIS(definitions.ObjectClass)
      case Boxed(LocalVar(v)) =>
        LOAD_LOCAL(v)
    }
  } /* class ClosureElim */


  /** Peephole optimization. */
  abstract class PeepholeOpt {
    /** Concrete implementations will perform their optimizations here */
    def peep(bb: BasicBlock, i1: Instruction, i2: Instruction): Option[List[Instruction]]

    var liveness: global.icodes.liveness.LivenessAnalysis = null

    def apply(m: IMethod): Unit = if (m.hasCode) {
      liveness = new global.icodes.liveness.LivenessAnalysis
      liveness.init(m)
      liveness.run()
      m foreachBlock transformBlock
    }

    def transformBlock(b: BasicBlock): Unit = if (b.size >= 2) {
      var newInstructions: List[Instruction] = b.toList
      var redo = false

      do {
        var h = newInstructions.head
        var t = newInstructions.tail
        var seen: List[Instruction] = Nil
        redo = false

        while (t != Nil) {
          peep(b, h, t.head) match {
            case Some(newInstrs) =>
              newInstructions = seen reverse_::: newInstrs ::: t.tail
              redo = true
            case None =>
            	()
          }
          seen = h :: seen
          h = t.head
          t = t.tail
        }
      } while (redo)
      b fromList newInstructions
    }
  }

} /* class ClosureElimination */