summaryrefslogtreecommitdiffstats
path: root/dx/src/com/android/jack/dx/ssa/back/SsaToRop.java
blob: 8175cf2c5f9f91700df41636b7ddc90d4cdc1508 (plain)
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.jack.dx.ssa.back;

import com.android.jack.dx.rop.code.BasicBlock;
import com.android.jack.dx.rop.code.BasicBlockList;
import com.android.jack.dx.rop.code.InsnList;
import com.android.jack.dx.rop.code.RegisterSpec;
import com.android.jack.dx.rop.code.RegisterSpecList;
import com.android.jack.dx.rop.code.Rop;
import com.android.jack.dx.rop.code.RopMethod;
import com.android.jack.dx.rop.code.Rops;
import com.android.jack.dx.ssa.BasicRegisterMapper;
import com.android.jack.dx.ssa.PhiInsn;
import com.android.jack.dx.ssa.RegisterMapper;
import com.android.jack.dx.ssa.SsaBasicBlock;
import com.android.jack.dx.ssa.SsaInsn;
import com.android.jack.dx.ssa.SsaMethod;
import com.android.jack.dx.util.Hex;
import com.android.jack.dx.util.IntList;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Comparator;

/**
 * Converts a method in SSA form to ROP form.
 */
public class SsaToRop {
  /** local debug flag */
  private static final boolean DEBUG = false;

  /** {@code non-null;} method to process */
  private final SsaMethod ssaMeth;

  /**
   * {@code true} if the converter should attempt to minimize
   * the rop-form register count
   */
  private final boolean minimizeRegisters;

  /** {@code non-null;} interference graph */
  private final InterferenceGraph interference;

  /**
   * Converts a method in SSA form to ROP form.
   *
   * @param ssaMeth {@code non-null;} method to process
   * @param minimizeRegisters {@code true} if the converter should
   * attempt to minimize the rop-form register count
   * @return {@code non-null;} rop-form output
   */
  public static RopMethod convertToRopMethod(SsaMethod ssaMeth, boolean minimizeRegisters) {
    return new SsaToRop(ssaMeth, minimizeRegisters).convert();
  }

  /**
   * Constructs an instance.
   *
   * @param ssaMethod {@code non-null;} method to process
   * @param minimizeRegisters {@code true} if the converter should
   * attempt to minimize the rop-form register count
   */
  private SsaToRop(SsaMethod ssaMethod, boolean minimizeRegisters) {
    this.minimizeRegisters = minimizeRegisters;
    this.ssaMeth = ssaMethod;
    this.interference = LivenessAnalyzer.constructInterferenceGraph(ssaMethod);
  }

  /**
   * Performs the conversion.
   *
   * @return {@code non-null;} rop-form output
   */
  private RopMethod convert() {
    if (DEBUG) {
      interference.dumpToStdout();
    }

    // These are other allocators for debugging or historical comparison:
    // allocator = new NullRegisterAllocator(ssaMeth, interference);
    // allocator = new FirstFitAllocator(ssaMeth, interference);

    RegisterAllocator allocator =
        new FirstFitLocalCombiningAllocator(ssaMeth, interference, minimizeRegisters);

    RegisterMapper mapper = allocator.allocateRegisters();

    if (DEBUG) {
      System.out.println("Printing reg map");
      System.out.println(((BasicRegisterMapper) mapper).toHuman());
    }

    ssaMeth.setBackMode();

    ssaMeth.mapRegisters(mapper);

    removePhiFunctions();

    if (allocator.wantsParamsMovedHigh()) {
      moveParametersToHighRegisters();
    }

    removeEmptyGotos();

    RopMethod ropMethod = new RopMethod(convertBasicBlocks(),
        ssaMeth.blockIndexToRopLabel(ssaMeth.getEntryBlockIndex()));
    ropMethod = new IdenticalBlockCombiner(ropMethod).process();

    return ropMethod;
  }

  /**
   * Removes all blocks containing only GOTOs from the control flow.
   * Although much of this work will be done later when converting
   * from rop to dex, not all simplification cases can be handled
   * there. Furthermore, any no-op block between the exit block and
   * blocks containing the real return or throw statements must be
   * removed.
   */
  private void removeEmptyGotos() {
    final ArrayList<SsaBasicBlock> blocks = ssaMeth.getBlocks();

    ssaMeth.forEachBlockDepthFirst(false, new SsaBasicBlock.Visitor() {
      @Override
      public void visitBlock(SsaBasicBlock b, SsaBasicBlock parent) {
        ArrayList<SsaInsn> insns = b.getInsns();

        if ((insns.size() == 1) && (insns.get(0).getOpcode() == Rops.GOTO)) {
          BitSet preds = (BitSet) b.getPredecessors().clone();

          for (int i = preds.nextSetBit(0); i >= 0; i = preds.nextSetBit(i + 1)) {
            SsaBasicBlock pb = blocks.get(i);
            pb.replaceSuccessor(b.getIndex(), b.getPrimarySuccessorIndex());
          }
        }
      }
    });
  }

  /**
   * See Appel 19.6. To remove the phi instructions in an edge-split
   * SSA representation we know we can always insert a move in a
   * predecessor block.
   */
  private void removePhiFunctions() {
    ArrayList<SsaBasicBlock> blocks = ssaMeth.getBlocks();

    for (SsaBasicBlock block : blocks) {
      // Add moves in all the pred blocks for each phi insn.
      block.forEachPhiInsn(new PhiVisitor(blocks));

      // Delete the phi insns.
      block.removeAllPhiInsns();
    }

    /*
     * After all move insns have been added, sort them so they don't
     * destructively interfere.
     */
    for (SsaBasicBlock block : blocks) {
      block.scheduleMovesFromPhis();
    }
  }

  /**
   * Helper for {@link #removePhiFunctions}: PhiSuccessorUpdater for
   * adding move instructions to predecessors based on phi insns.
   */
  private static class PhiVisitor implements PhiInsn.Visitor {
    private final ArrayList<SsaBasicBlock> blocks;

    public PhiVisitor(ArrayList<SsaBasicBlock> blocks) {
      this.blocks = blocks;
    }

    @Override
    public void visitPhiInsn(PhiInsn insn) {
      RegisterSpecList sources = insn.getSources();
      RegisterSpec result = insn.getResult();
      int sz = sources.size();

      for (int i = 0; i < sz; i++) {
        RegisterSpec source = sources.get(i);
        SsaBasicBlock predBlock = blocks.get(insn.predBlockIndexForSourcesIndex(i));

        predBlock.addMoveToEnd(result, source);
      }
    }
  }

  /**
   * Moves the parameter registers, which allocateRegisters() places
   * at the bottom of the frame, up to the top of the frame to match
   * Dalvik calling convention.
   */
  private void moveParametersToHighRegisters() {
    int paramWidth = ssaMeth.getParamWidth();
    BasicRegisterMapper mapper = new BasicRegisterMapper(ssaMeth.getRegCount());
    int regCount = ssaMeth.getRegCount();

    for (int i = 0; i < regCount; i++) {
      if (i < paramWidth) {
        mapper.addMapping(i, regCount - paramWidth + i, 1);
      } else {
        mapper.addMapping(i, i - paramWidth, 1);
      }
    }

    if (DEBUG) {
      System.out.printf("Moving %d registers from 0 to %d\n", Integer.valueOf(paramWidth),
          Integer.valueOf(regCount - paramWidth));
    }

    ssaMeth.mapRegisters(mapper);
  }

  /**
   * @return rop-form basic block list
   */
  private BasicBlockList convertBasicBlocks() {
    ArrayList<SsaBasicBlock> blocks = ssaMeth.getBlocks();

    // Exit block may be null.
    SsaBasicBlock exitBlock = ssaMeth.getExitBlock();

    ssaMeth.computeReachability();
    int ropBlockCount = ssaMeth.getCountReachableBlocks();

    // Don't count the exit block, if it exists and is reachable.
    ropBlockCount -= (exitBlock != null && exitBlock.isReachable()) ? 1 : 0;

    BasicBlockList result = new BasicBlockList(ropBlockCount);

    // Convert all the reachable blocks except the exit block.
    int ropBlockIndex = 0;
    for (SsaBasicBlock b : blocks) {
      if (b.isReachable() && b != exitBlock) {
        result.set(ropBlockIndex++, convertBasicBlock(b));
      }
    }

    // The exit block, which is discarded, must do nothing.
    if (exitBlock != null && exitBlock.getInsns().size() != 0) {
      throw new RuntimeException("Exit block must have no insns when leaving SSA form");
    }

    return result;
  }

  /**
   * Validates that a basic block is a valid end predecessor. It must
   * end in a RETURN or a THROW. Throws a runtime exception on error.
   *
   * @param b {@code non-null;} block to validate
   * @throws RuntimeException on error
   */
  private void verifyValidExitPredecessor(SsaBasicBlock b) {
    ArrayList<SsaInsn> insns = b.getInsns();
    SsaInsn lastInsn = insns.get(insns.size() - 1);
    Rop opcode = lastInsn.getOpcode();

    if (opcode.getBranchingness() != Rop.BRANCH_RETURN && opcode != Rops.THROW) {
      throw new RuntimeException("Exit predecessor must end" + " in valid exit statement.");
    }
  }

  /**
   * Converts a single basic block to rop form.
   *
   * @param block SSA block to process
   * @return {@code non-null;} ROP block
   */
  private BasicBlock convertBasicBlock(SsaBasicBlock block) {
    IntList successorList = block.getRopLabelSuccessorList();
    int primarySuccessorLabel = block.getPrimarySuccessorRopLabel();

    // Filter out any reference to the SSA form's exit block.

    // Exit block may be null.
    SsaBasicBlock exitBlock = ssaMeth.getExitBlock();
    int exitRopLabel = (exitBlock == null) ? -1 : exitBlock.getRopLabel();

    if (successorList.contains(exitRopLabel)) {
      if (successorList.size() > 1) {
        throw new RuntimeException(
            "Exit predecessor must have no other successors" + Hex.u2(block.getRopLabel()));
      } else {
        successorList = IntList.EMPTY;
        primarySuccessorLabel = -1;

        verifyValidExitPredecessor(block);
      }
    }

    successorList.setImmutable();

    BasicBlock result = new BasicBlock(block.getRopLabel(), convertInsns(block.getInsns()),
        successorList, primarySuccessorLabel);

    return result;
  }

  /**
   * Converts an insn list to rop form.
   *
   * @param ssaInsns {@code non-null;} old instructions
   * @return {@code non-null;} immutable instruction list
   */
  private InsnList convertInsns(ArrayList<SsaInsn> ssaInsns) {
    int insnCount = ssaInsns.size();
    InsnList result = new InsnList(insnCount);

    for (int i = 0; i < insnCount; i++) {
      result.set(i, ssaInsns.get(i).toRopInsn());
    }

    result.setImmutable();

    return result;
  }

  /**
   * <b>Note:</b> This method is not presently used.
   *
   * @return a list of registers ordered by most-frequently-used to
   * least-frequently-used. Each register is listed once and only
   * once.
   */
  public int[] getRegistersByFrequency() {
    int regCount = ssaMeth.getRegCount();
    Integer[] ret = new Integer[regCount];

    for (int i = 0; i < regCount; i++) {
      ret[i] = Integer.valueOf(i);
    }

    Arrays.sort(ret, new Comparator<Integer>() {
      @Override
      public int compare(Integer o1, Integer o2) {
        return ssaMeth.getUseListForRegister(o2.intValue()).size()
            - ssaMeth.getUseListForRegister(o1.intValue()).size();
      }
    });

    int result[] = new int[regCount];

    for (int i = 0; i < regCount; i++) {
      result[i] = ret[i].intValue();
    }

    return result;
  }
}