summaryrefslogtreecommitdiff
path: root/sources/scala/tools/nsc/backend/icode/BasicBlocks.scala
blob: 6fdbe98c5726f9022041246e98e4d79731019919 (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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
/* NSC -- new scala compiler
 * Copyright 2005 LAMP/EPFL
 * @author  Martin Odersky
 */

// $Id$

package scala.tools.nsc.backend.icode;

import scala.tools.nsc.ast._;
import scala.collection.mutable.Map;
import scala.tools.nsc.util.Position;

trait BasicBlocks: ICodes {
  import opcodes._;

  /** This class represents a basic block. Each
   *  basic block contains a list of instructions that are
   *  either executed all, or none. No jumps
   *  to/from the "middle" of the basic block are allowed.
   */
  class BasicBlock (theLabel: int, val code: Code) {

    /** The type stack at the begining of the block */
    var initialStack : TypeStack = null;

    /** The label of the block */
    val label = theLabel;

    /** The substitute variables of the block
     *  in the case of a recursive method */
    var substituteVars : List[Symbol] = null;

    /** The stack at the end of the block */
    var endStack : TypeStack = null;

    /** When set, the 'emit' methods will be ignored. */
    var ignore: Boolean = false;

    var preds: List[BasicBlock] = null;

    /** ICode instructions, used as temporary storage while emitting code.
     * Once closed is called, only the `instrs' array should be used.
     */
    private var instructionList: List[Instruction] = Nil;

    private var _lastInstruction: Instruction = null;

    private var closed: boolean = false;

    private var instrs: Array[Instruction] = _;

    // public:

    /** Compute an hashCode for the block */
    override def hashCode() = label;

    /** Apply a function to all the instructions of the block. */
    def traverse(f: Instruction => unit) = {
      assert(closed, "Traversing an open block!: ");
      instrs foreach f;
    }

    def traverseBackwards(f: Instruction => Unit) = {
      var i = instrs.length - 1;
      while (i >= 0) {
        f(instrs(i));
        i = i - 1
      }
    }

    /** The number of instructions in this basic block so far. */
    def size: Int =
      if (isClosed)
        instrs.length;
      else
        instructionList.length;

    /** Initialize the stack of the block, must be done before evaluation
     *  the type stack  */
    def initStack(stack : TypeStack) = {
      if (initialStack == null) {
        initialStack = stack;
        endStack = null;
      }
    }

    ///////////////////// Substitutions ///////////////////////

    /**
     * Replace the instruction at the given position. Used by labels when
     * they are anchored.
     */
    def replaceInstruction(pos: Int, instr: Instruction): Boolean = {
      assert(closed, "Instructions can be replaced only after the basic block is closed");

      instrs(pos) = instr;
      true
    }

    /**
     * Replace the given instruction with the new one.
     * Returns `true' if it actually changed something.
     */
    def replaceInstruction(oldInstr: Instruction, newInstr: Instruction): Boolean = {
      assert(closed, "Instructions can be replaced only after the basic block is closed");

      var i = 0;
      var changed = false;
      while (i < instrs.length && !changed) {
        if (instrs(i) == oldInstr) {
          instrs(i) = newInstr;
          changed = true;
        }
        i = i + 1;
      }
      changed
    }

    /** Replace all instructions found in the map. */
    def subst(map: Map[Instruction, Instruction]) =
      if (!closed) substOnList(map) else {
        var i = 0;
        while (i < instrs.length) {
          map get instrs(i) match {
            case Some(instr) => replaceInstruction(i, instr);
            case None => ();
          }
          i = i + 1;
        }
      }

    private def substOnList(map: Map[Instruction, Instruction]): Unit = {
      def subst(l: List[Instruction]): List[Instruction] = l match {
        case Nil => Nil
        case x :: xs =>
          map.get(x) match {
            case Some(newInstr) => newInstr :: subst(xs);
            case None => x :: subst(xs);
          }
      }

      instructionList = subst(instructionList);
    }

    ////////////////////// Emit //////////////////////


    /** Add a new instruction at the end of the block,
     *  using the same source position as the last emitted instruction
     */
    def emit(instr: Instruction): Unit = {
      if (!instructionList.isEmpty)
        emit(instr, instructionList.head.pos);
      else
        emit(instr, Position.NOPOS);
    }

    def emit(instr: Instruction, pos: Int) = {
      assert (!closed || ignore, "BasicBlock closed");

      if (!ignore) {
//        Console.println("block " + label + ": " + instr);
        instr.pos = pos;
        instructionList = instr :: instructionList;
        _lastInstruction = instr;
      }
    }

    /** Close the block */
    def close = {
       assert(instructionList.length > 0,
              "Empty block.");
      closed = true;
      instrs = toInstructionArray(instructionList.reverse);
    }

    def isEmpty: Boolean = instructionList.isEmpty;

    /** Enter ignore mode: new 'emit'ted instructions will not be
     * added to this basic block. It makes the generation of THROW
     * and RETURNs easier.
     */
    def enterIgnoreMode = ignore = true;

    def exitIgnoreMode = {
      assert(ignore, "Exit ignore mode when not in ignore mode.");
      ignore = false;
    }

    /** Return the last instruction of this basic block. */
    def lastInstruction =
      if (closed)
        instrs(instrs.length - 1)
      else
        instructionList.head;

    def firstInstruction =
      if (closed)
        instrs(0)
      else
        instructionList.last;

    /** Convert the list to an array */
    def toInstructionArray(l: List[Instruction]): Array[Instruction] = {
      var array = new Array[Instruction](l.length);
      var i: Int = 0;

      l foreach (x => { array(i) = x; i = i + 1 });
      array
    }

    def isClosed = closed;

    // TODO: Take care of exception handlers!
    def successors : List[BasicBlock] = if (isEmpty) Nil else
      lastInstruction match {
        case JUMP (where) => List(where);
        case CJUMP(success, failure, _, _) => failure::success::Nil;
        case CZJUMP(success, failure, _, _) => failure::success::Nil;
        case SWITCH(_,labels) => labels;
        case RETURN(_) => Nil;
        case THROW() => Nil;
        case _ =>
          if (isClosed)
	    global.abort("The last instruction is not a control flow instruction: " + lastInstruction);
          else Nil;
      }

    /** Returns the precessors of this block, in the current 'code' chunk.
     *  This is signifficant only if there are exception handlers, which live
     *  in different code 'chunks' than the rest of the method.
     */
    def predecessors: List[BasicBlock] = {
      if (preds == null)
        preds = code.blocks.elements.filter (p => (p.successors contains this)).toList;
      preds
    }

    override def equals(other: Any): Boolean = (
      other.isInstanceOf[BasicBlock] &&
      other.asInstanceOf[BasicBlock].label == label &&
      other.asInstanceOf[BasicBlock].code  == code
    );

    // Instead of it, rather use a printer
    def print() : unit = print(System.out);

    def print(out: java.io.PrintStream) : unit = {
      out.println("block #"+label+" :");
      instructionList.reverse.foreach(
        (i: Instruction) => out.println("  "+i));
      out.print("Successors: ");
      successors.foreach((x: BasicBlock) => out.print(" "+x.label.toString()));
      out.println();
    }

    def fullString: String = {
      val buf = new StringBuffer();
      buf.append("Block ").append(label.toString());
      buf.append("\nSuccessors: ").append(successors);
      buf.append("\nPredecessors: ").append(predecessors);
      buf.toString()
    }

    override def toString(): String = "" + label;
  }

}