## mars.tools
Class BHTSimulator

    java.lang.Object
      java.awt.Component
          java.awt.Container
              java.awt.Window
                  java.awt.Frame
                      javax.swing.JFrame
                          mars.tools.AbstractMarsToolAndApplication
                              mars.tools.BHTSimulator

All Implemented Interfaces:
  ActionListener, ImageObserver, MenuContainer, Serializable, EventListener, Observer, Accessible, RootPaneContainer, WindowConstants, MarsTool

    public class BHTSimulator

extends AbstractMarsToolAndApplication
implements ActionListener

A MARS tool for simulating branch prediction with a Branch History Table (BHT)

The simulation is based on observing the access to the instruction memory area (text segment). If a branch instruction is encountered, a prediction based on a BHT is performed. The outcome of the branch is compared with the prediction and the prediction is updated accordingly. Statistics about the correct and incorrect number of predictions can be obtained for each BHT entry. The number of entries in the BHT and the history that is considered for each prediction can be configured interactively. A change of the configuration however causes a re-initialization of the BHT.

The tool can be used to show how branch prediction works in case of loops and how effective such simple methods are. In case of nested loops the difference of BHT with 1 or 2 Bit history can be explored and visualized.

Author:
  ingo.kofler@itec.uni-klu.ac.at
See Also:
  Serialized Form

Nested Class Summary

Nested classes/interfaces inherited from class mars.tools.AbstractMarsToolAndApplication
`AbstractMarsToolAndApplication.ConnectButton, AbstractMarsToolAndApplication.EnterKeyListener`

Nested classes/interfaces inherited from class javax.swing.JFrame
`JFrame.AccessibleJFrame`

Nested classes/interfaces inherited from class java.awt.Frame
`Frame.AccessibleAWTFrame`

Nested classes/interfaces inherited from class java.awt.Window
`Window.AccessibleAWTWindow`

Nested classes/interfaces inherited from class java.awt.Container
`Container.AccessibleAWTContainer`

Nested classes/interfaces inherited from class java.awt.Component
`Component.AccessibleAWTComponent, Component.BaselineResizeBehavior, Component.BltBufferStrategy, Component.FlipBufferStrategy`

Field Summary
`static int` `BHT_DEFAULT_HISTORY` constant for the default history size
`static boolean` `BHT_DEFAULT_INITVAL` constant for the default inital value
`static int` `BHT_DEFAULT_SIZE` constant for the default size of the BHT
`static String` `BHT_HEADING` the heading of the tool
`static String` `BHT_NAME` the name of the tool
`static String` `BHT_VERSION` the version of the tool

Fields inherited from class mars.tools.AbstractMarsToolAndApplication
`connectButton, isBeingUsedAsAMarsTool, theWindow, thisMarsApp`

Fields inherited from class javax.swing.JFrame
`accessibleContext, EXIT_ON_CLOSE, rootPane, rootPaneCheckingEnabled`

Fields inherited from class java.awt.Frame
`CROSSHAIR_CURSOR, DEFAULT_CURSOR, E_RESIZE_CURSOR, HAND_CURSOR, ICONIFIED, MAXIMIZED_BOTH, MAXIMIZED_HORIZ, MAXIMIZED_VERT, MOVE_CURSOR, N_RESIZE_CURSOR, NE_RESIZE_CURSOR, NORMAL, NW_RESIZE_CURSOR, S_RESIZE_CURSOR, SE_RESIZE_CURSOR, SW_RESIZE_CURSOR, TEXT_CURSOR, W_RESIZE_CURSOR, WAIT_CURSOR`

Fields inherited from class java.awt.Component
`BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT`

Fields inherited from interface javax.swing.WindowConstants
`DISPOSE_ON_CLOSE, DO_NOTHING_ON_CLOSE, HIDE_ON_CLOSE`

Fields inherited from interface java.awt.image.ImageObserver
`ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH`

Constructor Summary
`BHTSimulator()` Creates a BHT Simulator with given name and heading.

Method Summary
`void` `actionPerformed(ActionEvent event)` Handles the actions when selecting another value in one of the two combo boxes.
`protected void` `addAsObserver()` Adds BHTSimulator as observer of the text segment.
`protected JComponent` `buildMainDisplayArea()` Creates a GUI and initialize the GUI with the default values.
`protected static int` `extractBranchAddress(ProgramStatement stmt)` Extracts the target address of the branch.
`String` `getName()` Returns the name of the tool.
`protected void` `handleExecBranchInst(int branchInstAddr, boolean branchTaken)` Handles the execution of the branch instruction.
`protected void` `handlePreBranchInst(ProgramStatement stmt)` Handles the execution branch instruction.
`protected static boolean` `isBranchInstruction(ProgramStatement stmt)` Determines if the instruction is a branch instruction or not.
`protected void` `processMIPSUpdate(Observable resource, AccessNotice notice)` Callback for text segment access by the MIPS simulator.
`protected void` `reset()` Performs a reset of the simulator.
`protected void` `resetSimulator()` Resets the simulator by clearing the GUI elements and resetting the BHT.
`protected static boolean` `willBranch(ProgramStatement stmt)` Checks if the branch instruction delivered as parameter will branch or not.

Methods inherited from class mars.tools.AbstractMarsToolAndApplication
`action, addAsObserver, addAsObserver, buildButtonAreaMarsTool, buildButtonAreaStandAlone, buildHeadingArea, deleteAsObserver, deleteAsObserver, getHelpComponent, go, initializePostGUI, initializePreGUI, isObserving, performSpecialClosingDuties, update, updateDisplay`

Methods inherited from class javax.swing.JFrame

`addImpl, createRootPane, frameInit, getAccessibleContext, getContentPane, getDefaultCloseOperation, getGlassPane, getGraphics, getJMenuBar, getLayeredPane, getRootPane, getTransferHandler, isDefaultLookAndFeelDecorated, isRootPaneCheckingEnabled, paramString, processWindowEvent, remove, repaint, setContentPane, setDefaultCloseOperation, setDefaultLookAndFeelDecorated, setGlassPane, setIconImage, setJMenuBar, setLayeredPane, setLayout, setRootPane, setRootPaneCheckingEnabled, setTransferHandler, update`

Methods inherited from class java.awt.Frame
`addNotify, getCursorType, getExtendedState, getFrames, getIconImage, getMaximizedBounds, getMenuBar, getState, getTitle, isResizable, isUndecorated, remove, removeNotify, setCursor, setExtendedState, setMaximizedBounds, setMenuBar, setResizable, setState, setTitle, setUndecorated`

Methods inherited from class java.awt.Window

`addPropertyChangeListener, addPropertyChangeListener, addWindowFocusListener, addWindowListener, addWindowStateListener, applyResourceBundle, applyResourceBundle, createBufferStrategy, createBufferStrategy, dispose, getBufferStrategy, getFocusableWindowState, getFocusCycleRootAncestor, getFocusOwner, getFocusTraversalKeys, getGraphicsConfiguration, getIconImages, getInputContext, getListeners, getLocale, getModalExclusionType, getMostRecentFocusOwner, getOwnedWindows, getOwner, getOwnerlessWindows, getToolkit, getWarningString, getWindowFocusListeners, getWindowListeners, getWindows, getWindowStateListeners, hide, isActive, isAlwaysOnTop, isAlwaysOnTopSupported, isFocusableWindow, isFocusCycleRoot, isFocused, isLocationByPlatform, isShowing, pack, paint, postEvent, processEvent, processWindowFocusEvent, processWindowStateEvent, removeWindowFocusListener, removeWindowListener, removeWindowStateListener, reshape, setAlwaysOnTop, setBounds, setBounds, setCursor, setFocusableWindowState, setFocusCycleRoot, setIconImages, setLocationByPlatform, setLocationRelativeTo, setMinimumSize, setModalExclusionType, setSize, setSize, setVisible, show, toBack, toFront`

Methods inherited from class java.awt.Container

`add, add, add, add, add, addContainerListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getAlignmentX, getAlignmentY, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalPolicy, getInsets, getLayout, getMaximumSize, getMinimumSize, getMousePosition, getPreferredSize, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, print, printComponents, processContainerEvent, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusTraversalKeys, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setFont, transferFocusBackward, transferFocusDownCycle, validate, validateTree`

Methods inherited from class java.awt.Component

`action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, contains, createImage, createImage, createVolatileImage, createVolatileImage, disable, disableEvents, dispatchEvent, enable, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBaseline, getBaselineResizeBehavior, getBounds, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getFontMetrics, getForeground, getHeight, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocation, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getSize, getTreeLock, getWidth, getX, getY, gotFocus, handleEvent, hasFocus, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isDoubleBuffered, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isOpaque, isPreferredSizeSet, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, prepareImage, prepareImage, printAll, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processKeyEvent, processMouseEvent, processMouseMotionEvent, processMouseWheelEvent, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resize, resize, setBackground, setComponentOrientation, setDropTarget, setEnabled, setFocusable, setFocusTraversalKeysEnabled, setForeground, setIgnoreRepaint, setLocale, setLocation, setLocation, setMaximumSize, setName, setPreferredSize, show, size, toString, transferFocus, transferFocusUpCycle`

Methods inherited from class java.lang.Object
`clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait`

Methods inherited from interface java.awt.MenuContainer
`getFont, postEvent`

Field Detail

### BHT_DEFAULT_SIZE

    public static final int BHT_DEFAULT_SIZE

  constant for the default size of the BHT

  See Also:
    Constant Field Values

### BHT_DEFAULT_HISTORY

    public static final int BHT_DEFAULT_HISTORY

  constant for the default history size

  See Also:
    Constant Field Values

### BHT_DEFAULT_INITVAL

    public static final boolean BHT_DEFAULT_INITVAL

  constant for the default inital value

  See Also:
    Constant Field Values

### BHT_NAME

    public static final String BHT_NAME

  the name of the tool

  See Also:
    Constant Field Values

### BHT_VERSION

    public static final String BHT_VERSION

  the version of the tool

  See Also:
    Constant Field Values

### BHT_HEADING

    public static final String BHT_HEADING

  the heading of the tool

  See Also:
    Constant Field Values

Constructor Detail

### BHTSimulator

    public BHTSimulator()

  Creates a BHT Simulator with given name and heading.

Method Detail

### addAsObserver

    protected void addAsObserver()

  Adds BHTSimulator as observer of the text segment.

  Overrides:
    `addAsObserver` in class `AbstractMarsToolAndApplication`

### buildMainDisplayArea

    protected JComponent buildMainDisplayArea()

  Creates a GUI and initialize the GUI with the default values.

  Specified by:
    `buildMainDisplayArea` in class `AbstractMarsToolAndApplication`

### getName

    public String getName()

  Returns the name of the tool.

  Specified by:
    `getName` in interface `MarsTool`
  Specified by:
    `getName` in class `AbstractMarsToolAndApplication`
  Returns:
    the tool's name as String

### reset

    protected void reset()

  Performs a reset of the simulator. This causes the BHT to be reseted and the log messages to be cleared.

  Overrides:
    `reset` in class `AbstractMarsToolAndApplication`

### actionPerformed

    public void actionPerformed(ActionEvent event)

  Handles the actions when selecting another value in one of the two combo boxes. Selecting a different BHT size or history causes a reset of the simulator.

  Specified by:
    `actionPerformed` in interface `ActionListener`

### resetSimulator

    protected void resetSimulator()

  Resets the simulator by clearing the GUI elements and resetting the BHT.

### handlePreBranchInst

    protected void handlePreBranchInst(ProgramStatement stmt)

  Handles the execution branch instruction. This method is called each time a branch instruction is executed. Based on the address of the instruction the corresponding index into the BHT is calculated. The prediction is obtained from the BHT at the calculated index and is visualized appropriately.

  Parameters:
    `stmt` - the branch statement that is executed

### handleExecBranchInst

    protected void handleExecBranchInst(int branchInstAddr,
                                        boolean branchTaken)

  Handles the execution of the branch instruction. The correctness of the prediction is visualized in both the table and the log message area. The BHT is updated based on the information if the branch instruction was taken or not.

  Parameters:
    `branchInstAddr` - the address of the branch instruction
    `branchTaken` - the information if the branch is taken or not (determined in a step before)

### isBranchInstruction

    protected static boolean isBranchInstruction(ProgramStatement stmt)

  Determines if the instruction is a branch instruction or not.

  Parameters:
    `stmt` - the statement to investigate
  Returns:
    true, if stmt is a branch instruction, otherwise false

### willBranch

    protected static boolean willBranch(ProgramStatement stmt)

  Checks if the branch instruction delivered as parameter will branch or not.

  Parameters:
    `stmt` - the branch instruction to be investigated
  Returns:
    true if the branch will be taken, otherwise false

### extractBranchAddress

    protected static int extractBranchAddress(ProgramStatement stmt)

  Extracts the target address of the branch. In MIPS the target address is encoded as 16-bit value. The target address is encoded relative to the address of the instruction after the branch instruction

  Parameters:
    `stmt` - the branch instruction
  Returns:
    the address of the instruction that is executed if the branch is taken

### processMIPSUpdate

    protected void processMIPSUpdate(Observable resource,
                                     AccessNotice notice)

  Callback for text segment access by the MIPS simulator. The method is called each time the text segment is accessed to fetch the next instruction. If the next instruction to execute was a branch instruction, the branch prediction is performed and visualized. In case the last instruction was a branch instruction, the outcome of the branch prediction is analyzed and visualized.

  Overrides:
    `processMIPSUpdate` in class `AbstractMarsToolAndApplication`
  Parameters:
    `resource` - the observed resource
    `notice` - signals the type of access (memory, register etc.)