summaryrefslogtreecommitdiff
path: root/src/compiler/scala/tools/nsc/backend/opt/ClosureElimination.scala
blob: 9a777ae4130aaae92d8d2dcc2ec236844616b3ac (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
236
237
238
239
240
241
 /* NSC -- new Scala compiler
 * Copyright 2005-2007 LAMP/EPFL
 * @author  Iulian Dragos
 */

// $Id$

package scala.tools.nsc.backend.opt;

import scala.collection.mutable.{Map, HashMap};
import scala.tools.nsc.backend.icode.analysis.LubError;
import scala.tools.nsc.symtab._;

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

  val phaseName = "closelim"

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

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

    def name = phaseName
    val closser = new ClosureElim

    override def apply(c: IClass): Unit =
      closser.analyzeClass(c)
  }

  /**
   * Remove references to the environemnt 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 {

    /* fresh name counter */
    var count = 0

    def freshName(s: String) = {
      val ret = s + this.count
      this.count += 1
      ret
    }

    /** A simple peephole optimizer. */
    val peephole = new PeepholeOpt( (i1, i2) =>
    	(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 (LOAD_LOCAL(_), DROP(_)) =>
          Some(Nil)

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

        case (LOAD_FIELD(sym, isStatic), DROP(_)) =>
        	if (isStatic)
            Some(Nil)
          else
            Some(DROP(REFERENCE(definitions.ObjectClass)) :: Nil);

        case _ => None
      });

    def analyzeClass(cls: IClass): Unit = if (settings.Xcloselim.value) {
      cls.methods.foreach { m =>
        analyzeMethod(m)
        peephole.transformMethod(m);
     }}


    val cpp = new copyPropagation.CopyAnalysis


    import copyPropagation._

    /* Some embryonic copy propagation. */
    def analyzeMethod(m: IMethod): Unit = try {if (m.code ne null) {
      log("Analyzing " + m)
      cpp.init(m)
      cpp.run

      for (bb <- linearizer.linearize(m)) {
        var info = cpp.in(bb)
        log("Cpp info at entry to block " + bb + ": " + info)

        for (i <- bb.toList) {
          i match {
            case LOAD_LOCAL(l) if (info.bindings.isDefinedAt(LocalVar(l))) =>
              val t = info.getBinding(l)
              t match {
                case Deref(LocalVar(v)) =>
                  bb.replaceInstruction(i, valueToInstruction(t));
                  log("replaced " + i + " with " + t)

                case Deref(This) =>
                  bb.replaceInstruction(i, valueToInstruction(t));
                  log("replaced " + i + " with " + t)

                case _ =>
                  bb.replaceInstruction(i, LOAD_LOCAL(info.getAlias(l)));
                  log("replaced " + i + " with " + info.getAlias(l))

              }

            case LOAD_FIELD(f, false) if accessible(f, m.symbol) =>
              info.stack(0) match {
                case r @ Record(cls, bindings) if bindings.isDefinedAt(f) =>
                  info.getFieldValue(r, f) match {
                    case Some(v) =>
                      bb.replaceInstruction(i,
                          DROP(REFERENCE(cls)) :: valueToInstruction(v) :: Nil);
                      log("Replaced " + i + " with " + info.getBinding(r, f));
                    case None => ();
                  }

                case Deref(LocalVar(l)) =>
                  info.getBinding(l) match {
                    case r @ Record(cls, bindings) if bindings.isDefinedAt(f) =>
                      info.getFieldValue(r, f) match {
                        case Some(v) =>
                          bb.replaceInstruction(i,
                              DROP(REFERENCE(cls)) :: valueToInstruction(v) :: Nil);
                          log("Replaced " + i + " with " + info.getBinding(r, f));
                        case None => ();
                      }
                    case _ => ();
                  }

                case _ => ();
              }

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

            case _ => ();
          }
          info = cpp.interpret(info, i)
        }
      }
    }} catch {
      case e: LubError =>
        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)
    }

    /** is field 'f' accessible from method 'm'? */
    def accessible(f: Symbol, m: Symbol): Boolean =
      f.isPublic || (f.hasFlag(Flags.PROTECTED) && (enclPackage(f) == enclPackage(m)))

    private def enclPackage(sym: Symbol): Symbol =
      if ((sym == NoSymbol) || sym.isPackageClass) sym else enclPackage(sym.owner)

  } /* class ClosureElim */


  /** Peephole optimization. */
  class PeepholeOpt(peep: (Instruction, Instruction) => Option[List[Instruction]]) {

    private var method: IMethod = null

    def transformMethod(m: IMethod): Unit = if (m.code ne null) {
      method = m
      for (b <- m.code.blocks)
        transformBlock(b)
    }

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

      newInstructions = 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(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 */