001/*
002 *  This file is part of the Jikes RVM project (http://jikesrvm.org).
003 *
004 *  This file is licensed to You under the Eclipse Public License (EPL);
005 *  You may not use this file except in compliance with the License. You
006 *  may obtain a copy of the License at
007 *
008 *      http://www.opensource.org/licenses/eclipse-1.0.php
009 *
010 *  See the COPYRIGHT.txt file distributed with this work for information
011 *  regarding copyright ownership.
012 */
013package org.jikesrvm.compilers.baseline;
014
015/**
016 * Profile data for a branch instruction.
017 */
018public final class SwitchBranchProfile extends BranchProfile {
019
020  /**
021   * The number of times that the different arms of a switch were
022   * taken. By convention, the default case is the last entry.
023   */
024  final float[] counts;
025
026  /**
027   * @param bci the bytecode index of the source branch instruction
028   * @param cs counts
029   * @param start idx of first entry in cs
030   * @param numEntries number of entries in cs for this switch
031   */
032  SwitchBranchProfile(int bci, int[] cs, int start, int numEntries) {
033    super(bci, sumCounts(cs, start, numEntries));
034    counts = new float[numEntries];
035    for (int i = 0; i < numEntries; i++) {
036      counts[i] = countToFloat(cs[start + i]);
037    }
038  }
039
040  public float getDefaultProbability() {
041    return getProbability(counts.length - 1);
042  }
043
044  public float getCaseProbability(int n) {
045    return getProbability(n);
046  }
047
048  float getProbability(int n) {
049    if (freq > 0) {
050      return counts[n] / freq;
051    } else {
052      return 1.0f / counts.length;
053    }
054  }
055
056  @Override
057  public String toString() {
058    StringBuilder result = new StringBuilder();
059    result.append(bci);
060    result.append("\tswitch     < ");
061    result.append((int) counts[0]);
062    for (int i = 1; i < counts.length; i++) {
063      result.append(", ");
064      result.append((int) counts[i]);
065    }
066    result.append(" >");
067    return result.toString();
068  }
069
070  private static float sumCounts(int[] counts, int start, int numEntries) {
071    float sum = 0.0f;
072    for (int i = start; i < start + numEntries; i++) {
073      sum += countToFloat(counts[i]);
074    }
075    return sum;
076  }
077}