Assignment-6 init

This commit is contained in:
karthikmurakonda 2022-10-31 21:41:27 +05:30
parent c25175fceb
commit f242de6bc8
65 changed files with 330242 additions and 0 deletions

22
assignment-6/.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,22 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "java",
"name": "Launch Current File",
"request": "launch",
"mainClass": "${file}",
"args": ["src/configuration/config.xml", "src/hello.txt", "supporting_files/test_cases/descending.out"]
},
{
"type": "java",
"name": "Launch Main",
"request": "launch",
"mainClass": "main.Main",
"projectName": "assignment-5_d93382a5"
}
]
}

Binary file not shown.

View File

@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- WARNING: Eclipse auto-generated file.
Any modifications will be overwritten.
To include a user specific buildfile here, simply create one in the same
directory with the processing instruction <?eclipse.ant.import?>
as the first entry and export the buildfile again. --><project basedir="." default="build">
<property environment="env"/>
<property name="debuglevel" value="source,lines,vars"/>
<property name="target" value="1.8"/>
<property name="source" value="1.8"/>
<target name="init">
<mkdir dir="bin"/>
<copy includeemptydirs="false" todir="bin">
<fileset dir="src">
<exclude name="**/*.launch"/>
<exclude name="**/*.java"/>
</fileset>
</copy>
</target>
<target name="clean">
<delete dir="bin"/>
</target>
<target depends="clean" name="cleanall"/>
<target depends="build-subprojects,build-project" name="build"/>
<target name="build-subprojects"/>
<target depends="init" name="build-project">
<javac debug="true" debuglevel="${debuglevel}" destdir="bin" includeantruntime="false" source="${source}" target="${target}">
<src path="src"/>
</javac>
</target>
<target name="make-jar" depends="build">
<mkdir dir="jars"/>
<jar destfile="jars/simulator.jar" basedir="bin">
<manifest>
<attribute name="Main-Class" value="main.Main"/>
</manifest>
</jar>
</target>
</project>

View File

@ -0,0 +1,43 @@
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<Configuration>
<FunctionalUnits>
<ALU>
<Count>2</Count>
<Latency>1</Latency>
<ReciprocalOfThroughput>1</ReciprocalOfThroughput>
</ALU>
<Multiplier>
<Count>1</Count>
<Latency>4</Latency>
<ReciprocalOfThroughput>1</ReciprocalOfThroughput>
</Multiplier>
<Divider>
<Count>1</Count>
<Latency>10</Latency>
<ReciprocalOfThroughput>1</ReciprocalOfThroughput>
</Divider>
</FunctionalUnits>
<L1iCache>
<NumberOfLines>256</NumberOfLines>
<Latency>2</Latency>
<Associativity>4</Associativity>
<ReplacementPolicy>LRU</ReplacementPolicy>
</L1iCache>
<L1dCache>
<NumberOfLines>256</NumberOfLines>
<Latency>2</Latency>
<Associativity>4</Associativity>
<ReplacementPolicy>LRU</ReplacementPolicy>
</L1dCache>
<L2Cache>
<NumberOfLines>2048</NumberOfLines>
<Latency>10</Latency>
<Associativity>4</Associativity>
<ReplacementPolicy>LRU</ReplacementPolicy>
</L2Cache>
<MainMemoryLatency>40</MainMemoryLatency>
</Configuration>

View File

@ -0,0 +1,4 @@
Number of instructions executed = 6
Number of cycles taken = 252
Number of data hazards = 7
Number of control hazards = 0

39
assignment-6/build.xml Normal file
View File

@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- WARNING: Eclipse auto-generated file.
Any modifications will be overwritten.
To include a user specific buildfile here, simply create one in the same
directory with the processing instruction <?eclipse.ant.import?>
as the first entry and export the buildfile again. --><project basedir="." default="build">
<property environment="env"/>
<property name="debuglevel" value="source,lines,vars"/>
<property name="target" value="1.8"/>
<property name="source" value="1.8"/>
<target name="init">
<mkdir dir="bin"/>
<copy includeemptydirs="false" todir="bin">
<fileset dir="src">
<exclude name="**/*.launch"/>
<exclude name="**/*.java"/>
</fileset>
</copy>
</target>
<target name="clean">
<delete dir="bin"/>
</target>
<target depends="clean" name="cleanall"/>
<target depends="build-subprojects,build-project" name="build"/>
<target name="build-subprojects"/>
<target depends="init" name="build-project">
<javac debug="true" debuglevel="${debuglevel}" destdir="bin" includeantruntime="false" source="${source}" target="${target}">
<src path="src"/>
</javac>
</target>
<target name="make-jar" depends="build">
<mkdir dir="jars"/>
<jar destfile="jars/simulator.jar" basedir="bin">
<manifest>
<attribute name="Main-Class" value="main.Main"/>
</manifest>
</jar>
</target>
</project>

BIN
assignment-6/report.pdf Normal file

Binary file not shown.

View File

@ -0,0 +1,116 @@
package configuration;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import generic.Misc;
public class Configuration {
public static int ALU_count;
public static int ALU_latency;
public static int ALU_reciprocal_of_throughput;
public static int multiplier_count;
public static int multiplier_latency;
public static int multiplier_reciprocal_of_throughput;
public static int divider_count;
public static int divider_latency;
public static int divider_reciprocal_of_throughput;
public static int L1i_numberOfLines;
public static int L1i_latency;
public static int L1i_associativity;
public static String L1i_replacementPolicy;
public static int L1d_numberOfLines;
public static int L1d_latency;
public static int L1d_associativity;
public static String L1d_replacementPolicy;
public static int L2_numberOfLines;
public static int L2_latency;
public static int L2_associativity;
public static String L2_replacementPolicy;
public static int mainMemoryLatency;
public static void parseConfiguratioFile(String configFileName)
{
Document doc = null;
try
{
File file = new File(configFileName);
DocumentBuilderFactory DBFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder DBuilder = DBFactory.newDocumentBuilder();
doc = DBuilder.parse(file);
doc.getDocumentElement().normalize();
}
catch(Exception e)
{
e.printStackTrace();
Misc.printErrorAndExit("Error in reading config file : " + e);
}
NodeList nodeLst = doc.getElementsByTagName("ALU");
Element elmnt = (Element) nodeLst.item(0);
ALU_count = Integer.parseInt(getImmediateString("Count", elmnt));
ALU_latency = Integer.parseInt(getImmediateString("Latency", elmnt));
ALU_reciprocal_of_throughput = Integer.parseInt(getImmediateString("ReciprocalOfThroughput", elmnt));
nodeLst = doc.getElementsByTagName("Multiplier");
elmnt = (Element) nodeLst.item(0);
multiplier_count = Integer.parseInt(getImmediateString("Count", elmnt));
multiplier_latency = Integer.parseInt(getImmediateString("Latency", elmnt));
multiplier_reciprocal_of_throughput = Integer.parseInt(getImmediateString("ReciprocalOfThroughput", elmnt));
nodeLst = doc.getElementsByTagName("Divider");
elmnt = (Element) nodeLst.item(0);
divider_count = Integer.parseInt(getImmediateString("Count", elmnt));
divider_latency = Integer.parseInt(getImmediateString("Latency", elmnt));
divider_reciprocal_of_throughput = Integer.parseInt(getImmediateString("ReciprocalOfThroughput", elmnt));
nodeLst = doc.getElementsByTagName("L1iCache");
elmnt = (Element) nodeLst.item(0);
L1i_numberOfLines = Integer.parseInt(getImmediateString("NumberOfLines", elmnt));
L1i_latency = Integer.parseInt(getImmediateString("Latency", elmnt));
L1i_associativity = Integer.parseInt(getImmediateString("Associativity", elmnt));
L1i_replacementPolicy = getImmediateString("ReplacementPolicy", elmnt);
nodeLst = doc.getElementsByTagName("L1dCache");
elmnt = (Element) nodeLst.item(0);
L1d_numberOfLines = Integer.parseInt(getImmediateString("NumberOfLines", elmnt));
L1d_latency = Integer.parseInt(getImmediateString("Latency", elmnt));
L1d_associativity = Integer.parseInt(getImmediateString("Associativity", elmnt));
L1d_replacementPolicy = getImmediateString("ReplacementPolicy", elmnt);
nodeLst = doc.getElementsByTagName("L2Cache");
elmnt = (Element) nodeLst.item(0);
L2_numberOfLines = Integer.parseInt(getImmediateString("NumberOfLines", elmnt));
L2_latency = Integer.parseInt(getImmediateString("Latency", elmnt));
L2_associativity = Integer.parseInt(getImmediateString("Associativity", elmnt));
L2_replacementPolicy = getImmediateString("ReplacementPolicy", elmnt);
nodeLst = doc.getElementsByTagName("Configuration");
elmnt = (Element) nodeLst.item(0);
mainMemoryLatency = Integer.parseInt(getImmediateString("MainMemoryLatency", elmnt));
}
private static String getImmediateString(String tagName, Element parent) // Get the immediate string value of a particular tag name under a particular parent tag
{
NodeList nodeLst = parent.getElementsByTagName(tagName);
if (nodeLst.item(0) == null)
{
Misc.printErrorAndExit("XML Configuration error : Item \"" + tagName + "\" not found inside the \"" + parent.getTagName() + "\" tag in the configuration file!!");
}
Element NodeElmnt = (Element) nodeLst.item(0);
NodeList resultNode = NodeElmnt.getChildNodes();
return ((Node) resultNode.item(0)).getNodeValue();
}
}

View File

@ -0,0 +1,43 @@
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<Configuration>
<FunctionalUnits>
<ALU>
<Count>2</Count>
<Latency>1</Latency>
<ReciprocalOfThroughput>1</ReciprocalOfThroughput>
</ALU>
<Multiplier>
<Count>1</Count>
<Latency>4</Latency>
<ReciprocalOfThroughput>1</ReciprocalOfThroughput>
</Multiplier>
<Divider>
<Count>1</Count>
<Latency>10</Latency>
<ReciprocalOfThroughput>1</ReciprocalOfThroughput>
</Divider>
</FunctionalUnits>
<L1iCache>
<NumberOfLines>256</NumberOfLines>
<Latency>2</Latency>
<Associativity>4</Associativity>
<ReplacementPolicy>LRU</ReplacementPolicy>
</L1iCache>
<L1dCache>
<NumberOfLines>256</NumberOfLines>
<Latency>2</Latency>
<Associativity>4</Associativity>
<ReplacementPolicy>LRU</ReplacementPolicy>
</L1dCache>
<L2Cache>
<NumberOfLines>2048</NumberOfLines>
<Latency>10</Latency>
<Associativity>4</Associativity>
<ReplacementPolicy>LRU</ReplacementPolicy>
</L2Cache>
<MainMemoryLatency>40</MainMemoryLatency>
</Configuration>

View File

@ -0,0 +1,7 @@
package generic;
public interface Element {
void handleEvent(Event event);
}

View File

@ -0,0 +1,51 @@
package generic;
public class Event {
public enum EventType {ExecutionComplete, MemoryRead, MemoryResponse, MemoryWrite};
long eventTime;
Element requestingElement;
Element processingElement;
EventType eventType;
public Event(long eventTime, EventType eventType, Element requestingElement, Element processingElement)
{
this.eventTime = eventTime;
this.eventType = eventType;
this.requestingElement = requestingElement;
this.processingElement = processingElement;
}
public long getEventTime() {
return eventTime;
}
public void setEventTime(long eventTime) {
this.eventTime = eventTime;
}
public Element getRequestingElement() {
return requestingElement;
}
public void setRequestingElement(Element requestingElement) {
this.requestingElement = requestingElement;
}
public Element getProcessingElement() {
return processingElement;
}
public void setProcessingElement(Element processingElement) {
this.processingElement = processingElement;
}
public EventType getEventType() {
return eventType;
}
public void setEventType(EventType eventType) {
this.eventType = eventType;
}
}

View File

@ -0,0 +1,50 @@
package generic;
import java.util.Comparator;
import java.util.PriorityQueue;
import processor.Clock;
public class EventQueue {
PriorityQueue<Event> queue;
public EventQueue()
{
queue = new PriorityQueue<Event>(new EventComparator());
}
public void addEvent(Event event)
{
queue.add(event);
}
public void processEvents()
{
while(queue.isEmpty() == false && queue.peek().getEventTime() <= Clock.getCurrentTime())
{
Event event = queue.poll();
event.getProcessingElement().handleEvent(event);
}
}
}
class EventComparator implements Comparator<Event>
{
@Override
public int compare(Event x, Event y)
{
if(x.getEventTime() < y.getEventTime())
{
return -1;
}
else if(x.getEventTime() > y.getEventTime())
{
return 1;
}
else
{
return 0;
}
}
}

View File

@ -0,0 +1,10 @@
package generic;
public class ExecutionCompleteEvent extends Event {
public ExecutionCompleteEvent(long eventTime, Element requestingElement, Element processingElement)
{
super(eventTime, EventType.ExecutionComplete, requestingElement, processingElement);
}
}

View File

@ -0,0 +1,96 @@
package generic;
public class Instruction {
public enum OperationType {add, addi, sub, subi, mul, muli, div, divi, and, andi, or, ori, xor, xori, slt, slti, sll, slli, srl, srli, sra, srai, load, store, jmp, beq, bne, blt, bgt, end};
int programCounter;
OperationType operationType;
Operand sourceOperand1;
Operand sourceOperand2;
Operand destinationOperand;
public int getProgramCounter() {
return programCounter;
}
public void setProgramCounter(int programCounter) {
this.programCounter = programCounter;
}
public OperationType getOperationType() {
return operationType;
}
public void setOperationType(OperationType operationType) {
this.operationType = operationType;
}
public Operand getSourceOperand1() {
return sourceOperand1;
}
public void setSourceOperand1(Operand sourceOperand1) {
this.sourceOperand1 = sourceOperand1;
}
public Operand getSourceOperand2() {
return sourceOperand2;
}
public void setSourceOperand2(Operand sourceOperand2) {
this.sourceOperand2 = sourceOperand2;
}
public Operand getDestinationOperand() {
return destinationOperand;
}
public void setDestinationOperand(Operand destinationOperand) {
this.destinationOperand = destinationOperand;
}
public String toString()
{
if(sourceOperand1 != null)
{
if(sourceOperand2 != null)
{
if(destinationOperand != null)
{
return "PC="+ programCounter + "\t" + operationType + "\t" + sourceOperand1 + "\t" + sourceOperand2 + "\t" + destinationOperand + "\n";
}
else
{
return "PC="+ programCounter + "\t" + operationType + "\t" + sourceOperand1 + "\t" + sourceOperand2 + "\tnull" + "\n";
}
}
else
{
if(destinationOperand != null)
{
return "PC="+ programCounter + "\t" + operationType + "\t" + sourceOperand1 + "\tnull" + "\t" + destinationOperand + "\n";
}
else
{
return "PC="+ programCounter + "\t" + operationType + "\t" + sourceOperand1 + "\tnull" + "\tnull" + "\n";
}
}
}
else
{
if(sourceOperand2 != null)
{
if(destinationOperand != null)
{
return "PC="+ programCounter + "\t" + operationType + "\tnull" + "\t" + sourceOperand2 + "\t" + destinationOperand + "\n";
}
else
{
return "PC="+ programCounter + "\t" + operationType + "\tnull" + "\t" + sourceOperand2 + "\tnull" + "\n";
}
}
else
{
if(destinationOperand != null)
{
return "PC="+ programCounter + "\t" + operationType + "\tnull" + "\tnull" + "\t" + destinationOperand + "\n";
}
else
{
return "PC="+ programCounter + "\t" + operationType + "\tnull" + "\tnull" + "\tnull" + "\n";
}
}
}
}
}

View File

@ -0,0 +1,19 @@
package generic;
public class MemoryReadEvent extends Event {
int addressToReadFrom;
public MemoryReadEvent(long eventTime, Element requestingElement, Element processingElement, int address) {
super(eventTime, EventType.MemoryRead, requestingElement, processingElement);
this.addressToReadFrom = address;
}
public int getAddressToReadFrom() {
return addressToReadFrom;
}
public void setAddressToReadFrom(int addressToReadFrom) {
this.addressToReadFrom = addressToReadFrom;
}
}

View File

@ -0,0 +1,20 @@
package generic;
public class MemoryResponseEvent extends Event {
int value;
public MemoryResponseEvent(long eventTime, Element requestingElement, Element processingElement, int value) {
super(eventTime, EventType.MemoryResponse, requestingElement, processingElement);
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}

View File

@ -0,0 +1,29 @@
package generic;
public class MemoryWriteEvent extends Event {
int addressToWriteTo;
int value;
public MemoryWriteEvent(long eventTime, Element requestingElement, Element processingElement, int address, int value) {
super(eventTime, EventType.MemoryWrite, requestingElement, processingElement);
this.addressToWriteTo = address;
this.value = value;
}
public int getAddressToWriteTo() {
return addressToWriteTo;
}
public void setAddressToWriteTo(int addressToWriteTo) {
this.addressToWriteTo = addressToWriteTo;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}

View File

@ -0,0 +1,10 @@
package generic;
public class Misc {
public static void printErrorAndExit(String message)
{
System.err.println(message);
System.exit(1);
}
}

View File

@ -0,0 +1,41 @@
package generic;
public class Operand {
public enum OperandType {Register, Immediate, Label};
OperandType operandType;
int value;
String labelValue; //only applicable for Label type;
//Note that Label type is only applicable for functional emulation of assembly file
public OperandType getOperandType() {
return operandType;
}
public void setOperandType(OperandType operandType) {
this.operandType = operandType;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public String getLabelValue() {
return labelValue;
}
public void setLabelValue(String labelValue) {
this.labelValue = labelValue;
}
public String toString()
{
if(operandType == OperandType.Register || operandType == OperandType.Immediate)
{
return "[" + operandType.toString() + ":" + value + "]";
}
else
{
return "[" + operandType.toString() + ":" + labelValue + "]";
}
}
}

View File

@ -0,0 +1,90 @@
package generic;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.DataInputStream;
import processor.Clock;
import processor.Processor;
public class Simulator {
static Processor processor;
static boolean simulationComplete;
static EventQueue eventQueue;
public static void setupSimulation(String assemblyProgramFile, Processor p)
{
eventQueue = new EventQueue();
Simulator.processor = p;
loadProgram(assemblyProgramFile);
simulationComplete = false;
}
static void loadProgram(String assemblyProgramFile)
{
/*
* 1. load the program into memory according to the program layout described
* in the ISA specification
* 2. set PC to the address of the first instruction in the main
* 3. set the following registers:
* x0 = 0
* x1 = 65535
* x2 = 65535
*/
try (
InputStream is = new FileInputStream(assemblyProgramFile);
){
DataInputStream d_is = new DataInputStream(is);
int address = -1;
while(d_is.available() > 0){
int next = d_is.readInt();
System.out.println(next);
if(address == -1){
processor.getRegisterFile().setProgramCounter(next);
}
else{
processor.getMainMemory().setWord(address, next);
}
address += 1;
}
processor.getRegisterFile().setValue(0, 0);
processor.getRegisterFile().setValue(1, 65535);
processor.getRegisterFile().setValue(2, 65535);
// Debug
System.out.println(processor.getRegisterFile().getProgramCounter());
System.out.println(processor.getMainMemory().getContentsAsString(0, 10));
} catch (Exception e) {
e.printStackTrace();
}
}
public static void simulate()
{
while(simulationComplete == false)
{
processor.getRWUnit().performRW();
processor.getMAUnit().performMA();
processor.getEXUnit().performEX();
eventQueue.processEvents();
processor.getOFUnit().performOF();
processor.getIFUnit().performIF();
Clock.incrementClock();
// Statistics.setNumberOfInstructions(Statistics.getNumberOfInstructions() + 1);
Statistics.setNumberOfCycles(Statistics.getNumberOfCycles() + 1);
}
}
public static void setSimulationComplete(boolean value)
{
simulationComplete = value;
}
public static EventQueue getEventQueue ( )
{
return eventQueue ;
}
}

View File

@ -0,0 +1,68 @@
package generic;
import java.io.PrintWriter;
public class Statistics {
// TODO add your statistics here
static int numberOfInstructions;
static int numberOfCycles;
static int datahazards;
static int controlhazards;
public static void printStatistics(String statFile)
{
try
{
PrintWriter writer = new PrintWriter(statFile);
writer.println("Number of instructions executed = " + numberOfInstructions);
writer.println("Number of cycles taken = " + numberOfCycles);
writer.println("Number of data hazards = " + datahazards);
writer.println("Number of control hazards = " + controlhazards);
// TODO add code here to print statistics in the output file
writer.close();
}
catch(Exception e)
{
Misc.printErrorAndExit(e.getMessage());
}
}
// TODO write functions to update statistics
public static int getNumberOfInstructions()
{
return numberOfInstructions;
}
public static int getNumberOfCycles()
{
return numberOfCycles;
}
public static void setNumberOfInstructions(int numberOfInstructions)
{
Statistics.numberOfInstructions = numberOfInstructions;
}
public static void setNumberOfCycles(int numberOfCycles) {
Statistics.numberOfCycles = numberOfCycles;
}
public static int getDatahazards() {
return datahazards;
}
public static void setDatahazards(int datahazards) {
Statistics.datahazards = datahazards;
}
public static int getControlhazards() {
return controlhazards;
}
public static void setControlhazards(int controlhazards) {
Statistics.controlhazards = controlhazards;
}
}

View File

@ -0,0 +1,4 @@
Number of instructions executed = 263
Number of cycles taken = 13761
Number of data hazards = 203
Number of control hazards = 164

View File

@ -0,0 +1,50 @@
package main;
import java.util.ArrayList;
import configuration.Configuration;
import generic.Misc;
import generic.Statistics;
import processor.Processor;
import processor.memorysystem.MainMemory;
import processor.pipeline.RegisterFile;
import generic.Simulator;
public class Main {
public static void main(String[] args) {
if(args.length != 3)
{
Misc.printErrorAndExit("usage: java -jar <path-to-jar-file> <path-to-config-file> <path-to-stat-file> <path-to-object-file>\n");
}
Configuration.parseConfiguratioFile(args[0]);
Processor processor = new Processor();
Simulator.setupSimulation(args[2], processor);
Simulator.simulate();
processor.printState(0, 30); // ((0, 0) refers to the range of main memory addresses we wish to print. this is an empty set.
Statistics.printStatistics(args[1]);
System.out.println("Hash of the Processor State = "+getHashCode(processor.getRegisterFile(), processor.getMainMemory()));
}
static int getHashCode(RegisterFile registerState, MainMemory memoryState) {
ArrayList<Integer> hash = new ArrayList<Integer>();
hash.add(registerState.getProgramCounter());
for(int i=0;i<32;i++) {
hash.add(registerState.getValue(i));
}
for(int i=0;i<65536;i++) {
hash.add(memoryState.getWord(i));
}
return hash.hashCode();
}
}

View File

@ -0,0 +1,15 @@
package processor;
public class Clock {
static long currentTime = 0;
public static void incrementClock()
{
currentTime++;
}
public static long getCurrentTime()
{
return currentTime;
}
}

View File

@ -0,0 +1,97 @@
package processor;
import processor.memorysystem.MainMemory;
import processor.pipeline.EX_IF_LatchType;
import processor.pipeline.EX_MA_LatchType;
import processor.pipeline.Execute;
import processor.pipeline.IF_EnableLatchType;
import processor.pipeline.IF_OF_LatchType;
import processor.pipeline.InstructionFetch;
import processor.pipeline.MA_RW_LatchType;
import processor.pipeline.MemoryAccess;
import processor.pipeline.OF_EX_LatchType;
import processor.pipeline.OperandFetch;
import processor.pipeline.RegisterFile;
import processor.pipeline.RegisterWrite;
public class Processor {
RegisterFile registerFile;
MainMemory mainMemory;
IF_EnableLatchType IF_EnableLatch;
IF_OF_LatchType IF_OF_Latch;
OF_EX_LatchType OF_EX_Latch;
EX_MA_LatchType EX_MA_Latch;
EX_IF_LatchType EX_IF_Latch;
MA_RW_LatchType MA_RW_Latch;
InstructionFetch IFUnit;
OperandFetch OFUnit;
Execute EXUnit;
MemoryAccess MAUnit;
RegisterWrite RWUnit;
public Processor()
{
registerFile = new RegisterFile();
mainMemory = new MainMemory();
IF_EnableLatch = new IF_EnableLatchType();
IF_OF_Latch = new IF_OF_LatchType();
OF_EX_Latch = new OF_EX_LatchType();
EX_MA_Latch = new EX_MA_LatchType();
EX_IF_Latch = new EX_IF_LatchType();
MA_RW_Latch = new MA_RW_LatchType();
IFUnit = new InstructionFetch(this, IF_EnableLatch, IF_OF_Latch, EX_IF_Latch);
OFUnit = new OperandFetch(this, IF_OF_Latch, OF_EX_Latch, IF_EnableLatch);
EXUnit = new Execute(this, OF_EX_Latch, EX_MA_Latch, EX_IF_Latch);
MAUnit = new MemoryAccess(this, EX_MA_Latch, MA_RW_Latch);
RWUnit = new RegisterWrite(this, MA_RW_Latch, IF_EnableLatch, EX_MA_Latch);
}
public void printState(int memoryStartingAddress, int memoryEndingAddress)
{
System.out.println(registerFile.getContentsAsString());
System.out.println(mainMemory.getContentsAsString(memoryStartingAddress, memoryEndingAddress));
}
public RegisterFile getRegisterFile() {
return registerFile;
}
public void setRegisterFile(RegisterFile registerFile) {
this.registerFile = registerFile;
}
public MainMemory getMainMemory() {
return mainMemory;
}
public void setMainMemory(MainMemory mainMemory) {
this.mainMemory = mainMemory;
}
public InstructionFetch getIFUnit() {
return IFUnit;
}
public OperandFetch getOFUnit() {
return OFUnit;
}
public Execute getEXUnit() {
return EXUnit;
}
public MemoryAccess getMAUnit() {
return MAUnit;
}
public RegisterWrite getRWUnit() {
return RWUnit;
}
}

View File

@ -0,0 +1,77 @@
package processor.memorysystem;
import generic.Element;
import generic.Event;
import generic.ExecutionCompleteEvent;
import generic.MemoryReadEvent;
import generic.MemoryResponseEvent;
import generic.MemoryWriteEvent;
import generic.Simulator;
import processor.Clock;
public class MainMemory implements Element{
int[] memory;
public MainMemory()
{
memory = new int[65536];
}
public int getWord(int address)
{
return memory[address];
}
public void setWord(int address, int value)
{
memory[address] = value;
}
public String getContentsAsString(int startingAddress, int endingAddress)
{
if(startingAddress == endingAddress)
return "";
StringBuilder sb = new StringBuilder();
sb.append("\nMain Memory Contents:\n\n");
for(int i = startingAddress; i <= endingAddress; i++)
{
sb.append(i + "\t\t: " + memory[i] + "\n");
}
sb.append("\n");
return sb.toString();
}
@Override
public void handleEvent(Event e) {
if (e.getEventType() == Event.EventType.MemoryRead) {
System.out.println("Memory Read Event Happening");
MemoryReadEvent event = (MemoryReadEvent) e ;
System.out.println(getWord(event.getAddressToReadFrom()));
Simulator.getEventQueue().addEvent(
new MemoryResponseEvent(
Clock.getCurrentTime(),
this,
event.getRequestingElement(),
getWord(event.getAddressToReadFrom())
)
);
}
else if(e.getEventType() == Event.EventType.MemoryWrite) {
System.out.println("Memory Write Event Happening");
MemoryWriteEvent event = (MemoryWriteEvent) e ;
System.out.println(getWord(event.getAddressToWriteTo()));
this.setWord(event.getAddressToWriteTo(), event.getValue());
Simulator.getEventQueue().addEvent(
new ExecutionCompleteEvent(
Clock.getCurrentTime(),
this,
event.getRequestingElement())
);
}
}
}

View File

@ -0,0 +1,27 @@
package processor.pipeline;
public class EX_IF_LatchType {
int pc;
boolean IF_enable;
public EX_IF_LatchType()
{
IF_enable = false;
}
public boolean isIF_enable() {
return IF_enable;
}
public void setIF_enable(boolean iF_enable) {
IF_enable = iF_enable;
}
public int getPC() {
return pc;
}
public void setPC(int pc) {
this.pc = pc;
}
}

View File

@ -0,0 +1,59 @@
package processor.pipeline;
import generic.Instruction;
import generic.Operand;
public class EX_MA_LatchType {
boolean MA_enable;
Operand op2;
Instruction instruction;
int aluResult;
boolean MA_busy;
public EX_MA_LatchType()
{
MA_enable = false;
}
public void setInstruction(Instruction instruction) {
this.instruction = instruction;
}
public Instruction getInstruction() {
return instruction;
}
public void setOp2(Operand op2) {
this.op2 = op2;
}
public Operand getOp2(){
return op2;
}
public void setALUResult(int aluResult) {
this.aluResult = aluResult;
}
public int getALUResult(){
return aluResult;
}
public boolean isMA_enable() {
return MA_enable;
}
public void setMA_enable(boolean mA_enable) {
MA_enable = mA_enable;
}
public boolean isMA_busy() {
return MA_busy;
}
public void setMA_busy(boolean mA_busy) {
MA_busy = mA_busy;
}
}

View File

@ -0,0 +1,214 @@
package processor.pipeline;
import processor.Processor;
import configuration.Configuration;
import generic.Element;
import generic.Event;
import generic.ExecutionCompleteEvent;
import generic.Instruction;
import generic.Simulator;
import generic.Statistics;
import generic.Instruction.OperationType;
import generic.Operand.OperandType;
public class Execute implements Element{
Processor containingProcessor;
OF_EX_LatchType OF_EX_Latch;
EX_MA_LatchType EX_MA_Latch;
EX_IF_LatchType EX_IF_Latch;
public Execute(Processor containingProcessor, OF_EX_LatchType oF_EX_Latch, EX_MA_LatchType eX_MA_Latch, EX_IF_LatchType eX_IF_Latch)
{
this.containingProcessor = containingProcessor;
this.OF_EX_Latch = oF_EX_Latch;
this.EX_MA_Latch = eX_MA_Latch;
this.EX_IF_Latch = eX_IF_Latch;
}
public void performEX()
{
if(OF_EX_Latch.isEX_enable()&& !OF_EX_Latch.isEX_busy())
{
OperationType alu_op = OF_EX_Latch.getInstruction().getOperationType();
long latency = 0;
switch (alu_op) {
case mul:
case muli:
latency = Configuration.multiplier_latency;
break;
case div:
case divi:
latency = Configuration.divider_latency;
break;
default:
latency = Configuration.ALU_latency;
break;
}
Simulator.getEventQueue().addEvent(new ExecutionCompleteEvent(latency, this, this));
OF_EX_Latch.setEX_busy(true);
EX_MA_Latch.setMA_enable(false);
}
}
@Override
public void handleEvent(Event e) {
if(EX_MA_Latch.isMA_busy()){
e.setEventTime(e.getEventTime()+1);
Simulator.getEventQueue().addEvent(e);
return;
}
int op1 = OF_EX_Latch.getOp1();
int op2 = OF_EX_Latch.getOp2();
int imm = OF_EX_Latch.getImm();
System.out.println("op1: "+op1+" op2: "+op2+" imm: "+imm);
Instruction instruction = OF_EX_Latch.getInstruction();
int cur_pc = containingProcessor.getRegisterFile().getProgramCounter();
int alu_result = 0;
System.out.println("EX: " + instruction);
OperationType alu_op = OF_EX_Latch.getInstruction().getOperationType();
System.out.println("ALU OP: " + alu_op);
boolean noma = false;
switch(alu_op)
{
case add: alu_result = op1 + op2; break;
case addi: alu_result = op1 + imm; break;
case sub: alu_result = op1 - op2; break;
case subi: alu_result = op1 - imm; break;
case mul: alu_result = op1 * op2; break;
case muli: alu_result = op1 * imm; break;
case div:
alu_result = op1 / op2;
containingProcessor.getRegisterFile().setValue(31, op1 % op2);
break;
case divi:
alu_result = op1 / imm;
containingProcessor.getRegisterFile().setValue(31, op1 % imm);
break;
case and: alu_result = op1 & op2; break;
case andi: alu_result = op1 & imm; break;
case or: alu_result = op1 | op2; break;
case ori: alu_result = op1 | imm; break;
case xor: alu_result = op1 ^ op2; break;
case xori: alu_result = op1 ^ imm; break;
case slt: alu_result= (op1 < op2) ? 1 : 0; break;
case slti: alu_result= (op1 < imm) ? 1 : 0; break;
case sll:
containingProcessor.getRegisterFile().setValue(31, (int) Math.pow(2, op2));
alu_result = op1 << op2;
break;
case slli:
containingProcessor.getRegisterFile().setValue(31, (int) Math.pow(2, imm));
alu_result = op1 << imm;
break;
case srl:
containingProcessor.getRegisterFile().setValue(31, op1 & (1 << (op2 - 1)));
alu_result = op1 >>> op2;
break;
case srli:
containingProcessor.getRegisterFile().setValue(31, op1 & (1 << (imm - 1)));
alu_result = op1 >>> imm;
break;
case sra:
containingProcessor.getRegisterFile().setValue(31, op1 & (1 << (op2 - 1)));
alu_result = op1 >> op2;
break;
case srai:
containingProcessor.getRegisterFile().setValue(31, op1 & (1 << (imm - 1)));
alu_result = op1 >> imm;
break;
case load: alu_result = op1 + imm; break;
case store: alu_result = op2 + imm; break;
case jmp:
{
OperandType optype = instruction.getSourceOperand1().getOperandType();
if (optype == OperandType.Register){
imm = containingProcessor.getRegisterFile().getValue(
instruction.getSourceOperand1().getValue());
}
else{
imm = OF_EX_Latch.getImm();
}
alu_result = cur_pc + imm ;
EX_IF_Latch.setIF_enable(true);
EX_IF_Latch.setPC(alu_result-1);
noma = true;
containingProcessor.getOFUnit().setProceed(false);
}
break;
case beq:
{
if(op1 == op2)
{
EX_IF_Latch.setIF_enable(true);
alu_result = cur_pc + imm;
EX_IF_Latch.setPC(alu_result-1);
noma = true;
containingProcessor.getOFUnit().setProceed(false);
}
}
break;
case bne:
{
if(op1 != op2)
{
alu_result = cur_pc + imm;
EX_IF_Latch.setIF_enable(true);
EX_IF_Latch.setPC(alu_result-1);
noma = true;
containingProcessor.getOFUnit().setProceed(false);
}
}
break;
case blt:
{
if(op1 < op2)
{
alu_result = cur_pc + imm;
EX_IF_Latch.setIF_enable(true);
EX_IF_Latch.setPC(alu_result-1);
noma = true;
containingProcessor.getOFUnit().setProceed(false);
}
}
break;
case bgt:
{
if(op1 > op2)
{
alu_result = cur_pc + imm;
EX_IF_Latch.setIF_enable(true);
EX_IF_Latch.setPC(alu_result-1);
noma = true;
containingProcessor.getOFUnit().setProceed(false);
}
}
break;
case end:
{
containingProcessor.getOFUnit().setisEnd(true);
break;
}
default:
break;
}
System.out.println("ALU RESULT: " + alu_result+"\n\n");
EX_MA_Latch.setALUResult(alu_result);
EX_MA_Latch.setInstruction(OF_EX_Latch.getInstruction());
if(!noma)
{
EX_MA_Latch.setMA_enable(true);
}else{
Statistics.setControlhazards(Statistics.getControlhazards()+2); // stall 2 cycles
}
OF_EX_Latch.setEX_busy(false);
}
}

View File

@ -0,0 +1,30 @@
package processor.pipeline;
public class IF_EnableLatchType {
boolean IF_enable;
boolean freeze;
public IF_EnableLatchType()
{
IF_enable = true;
freeze = false;
}
public boolean isIF_enable() {
return IF_enable;
}
public void setIF_enable(boolean iF_enable) {
IF_enable = iF_enable;
}
public boolean isFreeze() {
return freeze;
}
public void setFreeze(boolean freeze) {
this.freeze = freeze;
}
}

View File

@ -0,0 +1,56 @@
package processor.pipeline;
public class IF_OF_LatchType {
boolean OF_enable;
int instruction;
boolean IF_busy=false;
boolean IF_branching_busy=false;
boolean OF_busy=false;
public IF_OF_LatchType()
{
OF_enable = false;
}
public boolean isOF_enable() {
return OF_enable;
}
public void setOF_enable(boolean oF_enable) {
OF_enable = oF_enable;
}
public int getInstruction() {
return instruction;
}
public void setInstruction(int instruction) {
this.instruction = instruction;
}
public boolean isIF_busy() {
return IF_busy;
}
public void setIF_busy(boolean iF_busy) {
IF_busy = iF_busy;
}
public boolean isIF_branching_busy() {
return IF_branching_busy;
}
public void setIF_branching_busy(boolean iF_branching_busy) {
IF_branching_busy = iF_branching_busy;
}
public boolean isOF_busy() {
return OF_busy;
}
public void setOF_busy(boolean oF_busy) {
OF_busy = oF_busy;
}
}

View File

@ -0,0 +1,102 @@
package processor.pipeline;
import configuration.Configuration;
import generic.Element;
import generic.Event;
import generic.MemoryReadEvent;
import generic.MemoryResponseEvent;
import generic.Simulator;
import generic.Statistics;
import processor.Clock;
import processor.Processor;
public class InstructionFetch implements Element{
Processor containingProcessor;
IF_EnableLatchType IF_EnableLatch;
IF_OF_LatchType IF_OF_Latch;
EX_IF_LatchType EX_IF_Latch;
public InstructionFetch(Processor containingProcessor, IF_EnableLatchType iF_EnableLatch, IF_OF_LatchType iF_OF_Latch, EX_IF_LatchType eX_IF_Latch)
{
this.containingProcessor = containingProcessor;
this.IF_EnableLatch = iF_EnableLatch;
this.IF_OF_Latch = iF_OF_Latch;
this.EX_IF_Latch = eX_IF_Latch;
}
public void performIF()
{
if(EX_IF_Latch.isIF_enable() && !IF_OF_Latch.isIF_branching_busy() &&!IF_OF_Latch.isIF_busy()){
containingProcessor.getRegisterFile().setProgramCounter(EX_IF_Latch.getPC());
int currentPC = containingProcessor.getRegisterFile().getProgramCounter();
Simulator.getEventQueue().addEvent(
new MemoryReadEvent(
Clock.getCurrentTime()+Configuration.mainMemoryLatency,
this,
containingProcessor.getMainMemory(),
currentPC
)
);
System.out.println("H1");
IF_OF_Latch.setIF_branching_busy(true);
EX_IF_Latch.setIF_enable(false);
IF_OF_Latch.setOF_enable(false);
System.out.println("IF: PC set to " + EX_IF_Latch.getPC());
} // if EX_IF_Latch is enabled, set PC to EX_IF_Latch's PC and wait for next cycle (1 nop)
else if(IF_EnableLatch.isIF_enable())
{
if(!IF_EnableLatch.isFreeze()){
if(IF_OF_Latch.isIF_busy()){
return;
}
int currentPC = containingProcessor.getRegisterFile().getProgramCounter();
Simulator.getEventQueue().addEvent(
new MemoryReadEvent(
Clock.getCurrentTime()+ Configuration.mainMemoryLatency,
this,
containingProcessor.getMainMemory(),
currentPC
)
);
System.out.println("H2");
IF_OF_Latch.setIF_busy(true);
IF_OF_Latch.setOF_enable(false);
}else{
IF_EnableLatch.setFreeze(false);
}
}
}
@Override
public void handleEvent(Event e) {
if(IF_OF_Latch.isOF_busy()|| IF_EnableLatch.isFreeze()){
e.setEventTime(Clock.getCurrentTime()+1);
Simulator.getEventQueue().addEvent(e);
IF_EnableLatch.setFreeze(false);
IF_OF_Latch.setOF_enable(true);
return;
}
if(IF_OF_Latch.isIF_branching_busy()){
IF_EnableLatch.setFreeze(false);
IF_OF_Latch.setIF_branching_busy(false);
containingProcessor.getOFUnit().Proceed = true;
System.out.println("IF: Unfreezing");
return;
}
MemoryResponseEvent event = (MemoryResponseEvent) e;
Statistics.setNumberOfInstructions(Statistics.getNumberOfInstructions()+1);
IF_OF_Latch.setInstruction(event.getValue());
containingProcessor.getRegisterFile().setProgramCounter(containingProcessor.getRegisterFile().getProgramCounter() + 1);
IF_OF_Latch.setOF_enable(true);
IF_OF_Latch.setIF_busy(false);
IF_EnableLatch.setFreeze(false);
}
}

View File

@ -0,0 +1,49 @@
package processor.pipeline;
import generic.Instruction;
public class MA_RW_LatchType {
boolean RW_enable;
int aluResult;
int load_result;
Instruction instruction;
public MA_RW_LatchType()
{
RW_enable = false;
}
public boolean isRW_enable() {
return RW_enable;
}
public void setRW_enable(boolean rW_enable) {
RW_enable = rW_enable;
}
public void setALU_result(int alu_result) {
this.aluResult = alu_result;
}
public int getALU_result() {
return aluResult;
}
public void setLoad_result(int load_result) {
this.load_result = load_result;
}
public int getLoad_result() {
return load_result;
}
public void setInstruction(Instruction instruction) {
this.instruction = instruction;
}
public Instruction getInstruction() {
return instruction;
}
}

View File

@ -0,0 +1,83 @@
package processor.pipeline;
import configuration.Configuration;
import generic.Element;
import generic.Event;
import generic.ExecutionCompleteEvent;
import generic.Instruction;
import generic.MemoryReadEvent;
import generic.MemoryResponseEvent;
import generic.MemoryWriteEvent;
import generic.Simulator;
import processor.Clock;
import processor.Processor;
import generic.Instruction.OperationType;
public class MemoryAccess implements Element {
Processor containingProcessor;
EX_MA_LatchType EX_MA_Latch;
MA_RW_LatchType MA_RW_Latch;
public MemoryAccess(Processor containingProcessor, EX_MA_LatchType eX_MA_Latch, MA_RW_LatchType mA_RW_Latch)
{
this.containingProcessor = containingProcessor;
this.EX_MA_Latch = eX_MA_Latch;
this.MA_RW_Latch = mA_RW_Latch;
}
public void performMA()
{
if(EX_MA_Latch.isMA_enable()&& !EX_MA_Latch.isMA_busy())
{
Instruction instruction = EX_MA_Latch.getInstruction();
int alu_result = EX_MA_Latch.getALUResult();
MA_RW_Latch.setALU_result(alu_result);
OperationType op_type = instruction.getOperationType();
MA_RW_Latch.setInstruction(instruction);
MA_RW_Latch.setRW_enable(true);
if (op_type==OperationType.store)
{
int val_store = containingProcessor.getRegisterFile().getValue(
instruction.getSourceOperand1().getValue());
Simulator.getEventQueue().addEvent(
new MemoryWriteEvent(
Clock.getCurrentTime()+Configuration.mainMemoryLatency,
this,
containingProcessor.getMainMemory(),
alu_result,
val_store
)
);
EX_MA_Latch.setMA_busy(true);
MA_RW_Latch.setRW_enable(false);
}
else if (op_type==OperationType.load)
{
Simulator.getEventQueue().addEvent(
new MemoryReadEvent(
Clock.getCurrentTime()+Configuration.mainMemoryLatency,
this,
containingProcessor.getMainMemory(),
alu_result
)
);
EX_MA_Latch.setMA_busy(true);
MA_RW_Latch.setRW_enable(false);
}
}
}
@Override
public void handleEvent(Event e) {
if(e instanceof ExecutionCompleteEvent) {
EX_MA_Latch.setMA_busy(false);
MA_RW_Latch.setRW_enable(true);
return;
}
MemoryResponseEvent event=(MemoryResponseEvent) e;
MA_RW_Latch.setLoad_result(event.getValue());
MA_RW_Latch.setRW_enable(true);
}
}

View File

@ -0,0 +1,65 @@
package processor.pipeline;
import generic.Instruction;
public class OF_EX_LatchType {
boolean EX_enable;
Instruction instruction;
int op1, op2, imm;
boolean EX_busy=false;
public OF_EX_LatchType()
{
EX_enable = false;
}
public void setInstruction(Instruction instruction) {
this.instruction = instruction;
}
public Instruction getInstruction() {
return instruction;
}
public void setOp1(int op1) {
this.op1 = op1;
}
public int getOp1() {
return op1;
}
public void setOp2(int op2) {
this.op2 = op2;
}
public int getOp2() {
return op2;
}
public void setImm(int imm) {
this.imm = imm;
}
public int getImm() {
return imm;
}
public boolean isEX_enable() {
return EX_enable;
}
public void setEX_enable(boolean eX_enable) {
EX_enable = eX_enable;
}
public boolean isEX_busy() {
return EX_busy;
}
public void setEX_busy(boolean isEX_busy) {
this.EX_busy = isEX_busy;
}
}

View File

@ -0,0 +1,227 @@
package processor.pipeline;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import generic.Instruction;
import processor.Processor;
import generic.Instruction.OperationType;
import generic.Operand.OperandType;
import generic.Operand;
import generic.Statistics;
public class OperandFetch {
Processor containingProcessor;
IF_OF_LatchType IF_OF_Latch;
OF_EX_LatchType OF_EX_Latch;
IF_EnableLatchType IF_EnableLatch;
static OperationType[] opTypes = OperationType.values();
public boolean Proceed;
Queue<Integer> queue;
boolean isEnd;
public OperandFetch(Processor containingProcessor, IF_OF_LatchType iF_OF_Latch, OF_EX_LatchType oF_EX_Latch, IF_EnableLatchType iF_EnableLatch)
{
this.containingProcessor = containingProcessor;
this.IF_OF_Latch = iF_OF_Latch;
this.OF_EX_Latch = oF_EX_Latch;
this.IF_EnableLatch = iF_EnableLatch;
isEnd = false;
Proceed = true;
queue = new LinkedList<>();
queue.add(-1);
queue.add(-1);
queue.add(-1);
queue.add(-1);
queue.add(-1);
}
boolean checkdatahazard(int[] operands) {
for(int i=0;i<operands.length;i++) {
if(queue.contains(operands[i])) {
return true;
}
}
return false;
}
void updateQueue(int operand) {
queue.poll();
queue.add(operand);
}
public static int twoscompliment(String s) {
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (chars[i] == '0') {
chars[i] = '1';
} else {
chars[i] = '0';
}
}
String s1 = new String(chars);
int num = Integer.parseInt(s1, 2);
num = num + 1;
return num;
}
public void performOF()
{
if(isEnd){
IF_EnableLatch.setIF_enable(false);
IF_OF_Latch.setOF_enable(false);
OF_EX_Latch.setEX_enable(false);
return;
}
if(OF_EX_Latch.isEX_busy()) {
IF_OF_Latch.setOF_busy(true);
return;
}else{
IF_OF_Latch.setOF_busy(false);
}
int addtoqueue = -1;
boolean noDataHazard = true;
if(IF_OF_Latch.isOF_enable() && Proceed && !IF_OF_Latch.isOF_busy())
{
int instruction = IF_OF_Latch.getInstruction();
Instruction instr = new Instruction();
String bin_instr = Integer.toBinaryString(instruction);
if (bin_instr.length() < 32) {
int diff = 32 - bin_instr.length();
String zeros = "";
for (int i = 0; i < diff; i++) {
zeros += "0";
}
bin_instr = zeros + bin_instr;
}
instr.setProgramCounter(containingProcessor.getRegisterFile().getProgramCounter());
int opcode = Integer.parseInt(bin_instr.substring(0, 5), 2);
instr.setOperationType(opTypes[opcode]);
int R3_type_operators[] = {0,2,4,6,8,10,12,14,16,18,20};
int R2I_type_operators[] = {1,3,5,7,9,11,13,15,17,19,21,22,23,25,26,27,28};
int R1I_type_operators[] = {24,29};
// check if the instruction is of type R3
if (Arrays.stream(R3_type_operators).anyMatch(x -> x == opcode)) {
Operand rs1 = new Operand();
Operand rs2 = new Operand();
Operand rd = new Operand();
rs1.setOperandType(Operand.OperandType.Register);
rs2.setOperandType(Operand.OperandType.Register);
rd.setOperandType(Operand.OperandType.Register);
rs1.setValue(Integer.parseInt(bin_instr.substring(5, 10), 2));
rs2.setValue(Integer.parseInt(bin_instr.substring(10, 15), 2));
rd.setValue(Integer.parseInt(bin_instr.substring(15, 20), 2));
int op1 = containingProcessor.getRegisterFile().getValue(rs1.getValue());
int op2 = containingProcessor.getRegisterFile().getValue(rs2.getValue());
if (checkdatahazard(new int[] { rs1.getValue(), rs2.getValue() })) {
noDataHazard = false;
}else{
addtoqueue = rd.getValue();
OF_EX_Latch.setInstruction(instr);
OF_EX_Latch.setOp1(op1);
OF_EX_Latch.setOp2(op2);
instr.setDestinationOperand(rd);
instr.setSourceOperand1(rs1);
instr.setSourceOperand2(rs2);
}
}
else if (Arrays.stream(R2I_type_operators).anyMatch(x -> x == opcode)) {
Operand rs1 = new Operand();
Operand rd = new Operand();
rs1.setOperandType(Operand.OperandType.Register);
rd.setOperandType(Operand.OperandType.Register);
rs1.setValue(Integer.parseInt(bin_instr.substring(5, 10), 2));
rd.setValue(Integer.parseInt(bin_instr.substring(10, 15), 2));
// check 15th bit to see if it is negative
int imm = Integer.parseInt(bin_instr.substring(15, 32), 2);
if (bin_instr.charAt(15)=='1'){
imm = -1*twoscompliment(bin_instr.substring(15, 32));
System.out.println(bin_instr);
}
int op1 = containingProcessor.getRegisterFile().getValue(rs1.getValue());
int op2 = containingProcessor.getRegisterFile().getValue(rd.getValue());
// System.out.println("imm: " + imm);
if (checkdatahazard(new int[] { rs1.getValue(), rd.getValue()})){
noDataHazard = false;
}else{
if(opcode <= 22) { // > 21 means it is a branch instruction so no need to update queue
addtoqueue = rd.getValue();
}
OF_EX_Latch.setInstruction(instr);
OF_EX_Latch.setImm(imm);
OF_EX_Latch.setOp1(op1);
OF_EX_Latch.setOp2(op2);
instr.setDestinationOperand(rd);
instr.setSourceOperand1(rs1);
}
}
else if (Arrays.stream(R1I_type_operators).anyMatch(x -> x == opcode)) {
if(opcode != 24){ // end
Operand rd = new Operand();
rd.setOperandType(Operand.OperandType.Register);
rd.setValue(Integer.parseInt(bin_instr.substring(5, 10), 2));
instr.setDestinationOperand(rd);
OF_EX_Latch.setInstruction(instr);
}
else{ // opcode == 24 jmp
Operand op = new Operand();
String imm = bin_instr.substring(10, 32);
int imm_val = Integer.parseInt(imm, 2);
if (imm.charAt(0) == '1'){
imm_val = -1*twoscompliment(imm);
}
if (imm_val != 0){
op.setOperandType(OperandType.Immediate);
op.setValue(imm_val);
instr.setSourceOperand1(op);
}
else{
op.setOperandType(OperandType.Register);
op.setValue(Integer.parseInt(bin_instr.substring(5, 10), 2));
instr.setSourceOperand1(op);
}
if (checkdatahazard(new int[] { op.getValue() })) {
noDataHazard = false;
}else{
OF_EX_Latch.setInstruction(instr);
OF_EX_Latch.setImm(imm_val);
}
}
}
OF_EX_Latch.setEX_enable(noDataHazard);
if(!noDataHazard){
IF_EnableLatch.setFreeze(true);
Statistics.setDatahazards(Statistics.getDatahazards() + 1);
}
updateQueue(addtoqueue);
}
else if (!Proceed) {
OF_EX_Latch.setEX_enable(false);
}else{
OF_EX_Latch.setEX_enable(false);
}
}
public void setisEnd(boolean isEnd) {
this.isEnd = isEnd;
}
public void setProceed(boolean proceed) {
Proceed = proceed;
if (!Proceed) {
OF_EX_Latch.setEX_enable(false);
}
}
}

View File

@ -0,0 +1,52 @@
package processor.pipeline;
public class RegisterFile {
int[] registerFile;
int programCounter;
public RegisterFile()
{
registerFile = new int[32];
registerFile[0]=0; //%xo is always 0 [RISC V]
}
public int getValue(int registerNumber)
{
return registerFile[registerNumber];
}
public void setValue(int registerNumber, int value)
{
registerFile[registerNumber] = value;
}
public int getProgramCounter()
{
return programCounter;
}
public void setProgramCounter(int programCounter)
{
this.programCounter = programCounter;
}
public void incrementProgramCounter()
{
this.programCounter++;
}
public String getContentsAsString()
{
StringBuilder sb = new StringBuilder();
sb.append("\nRegister File Contents:\n\n");
sb.append("PC" + "\t: " + programCounter + "\n\n");
sb.append("x" + 0 + "\t: " + registerFile[0]+ "\n"); //%xo is always 0 [RISC V]
for(int i = 1; i < 32; i++)
{
sb.append("x" + i + "\t: " + registerFile[i] + "\n");
}
sb.append("\n");
return sb.toString();
}
}

View File

@ -0,0 +1,66 @@
package processor.pipeline;
import generic.Simulator;
import generic.Instruction;
import generic.Instruction.OperationType;
import processor.Processor;
public class RegisterWrite {
Processor containingProcessor;
MA_RW_LatchType MA_RW_Latch;
IF_EnableLatchType IF_EnableLatch;
EX_MA_LatchType EX_MA_Latch;
public RegisterWrite(Processor containingProcessor, MA_RW_LatchType mA_RW_Latch, IF_EnableLatchType iF_EnableLatch, EX_MA_LatchType eX_MA_Latch)
{
this.containingProcessor = containingProcessor;
this.MA_RW_Latch = mA_RW_Latch;
this.IF_EnableLatch = iF_EnableLatch;
this.EX_MA_Latch = eX_MA_Latch;
}
public void performRW()
{
if(MA_RW_Latch.isRW_enable())
{
Instruction instruction = MA_RW_Latch.getInstruction();
OperationType op_type = instruction.getOperationType();
int alu_result = MA_RW_Latch.getALU_result();
boolean proceed = true;
if (op_type==OperationType.load)
{
EX_MA_Latch.setMA_busy(false);
int load_result = MA_RW_Latch.getLoad_result();
int rd = instruction.getDestinationOperand().getValue();
containingProcessor.getRegisterFile().setValue(rd, load_result);
}
else if (op_type==OperationType.end)
{
Simulator.setSimulationComplete(true);
proceed = false;
}
else
{
if (op_type!=OperationType.store && op_type!= OperationType.jmp && op_type!= OperationType.beq && op_type!=OperationType.bne && op_type!=OperationType.blt && op_type!=OperationType.bgt)
{
int rd = instruction.getDestinationOperand().getValue();
rd = instruction.getDestinationOperand().getValue();
containingProcessor.getRegisterFile().setValue(rd, alu_result);
}
}
IF_EnableLatch.setIF_enable(proceed);
}else{
try{
if(MA_RW_Latch.getInstruction().getOperationType() == OperationType.end){
IF_EnableLatch.setIF_enable(false);
}
else{
IF_EnableLatch.setIF_enable(true);
}
} catch(Exception e){
IF_EnableLatch.setIF_enable(true);
}
}
}
}

View File

@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- WARNING: Eclipse auto-generated file.
Any modifications will be overwritten.
To include a user specific buildfile here, simply create one in the same
directory with the processing instruction <?eclipse.ant.import?>
as the first entry and export the buildfile again. --><project basedir="." default="build">
<property environment="env"/>
<property name="debuglevel" value="source,lines,vars"/>
<property name="target" value="1.8"/>
<property name="source" value="1.8"/>
<target name="init">
<mkdir dir="bin"/>
<copy includeemptydirs="false" todir="bin">
<fileset dir="src">
<exclude name="**/*.launch"/>
<exclude name="**/*.java"/>
</fileset>
</copy>
</target>
<target name="clean">
<delete dir="bin"/>
</target>
<target depends="clean" name="cleanall"/>
<target depends="build-subprojects,build-project" name="build"/>
<target name="build-subprojects"/>
<target depends="init" name="build-project">
<javac debug="true" debuglevel="${debuglevel}" destdir="bin" includeantruntime="false" source="${source}" target="${target}">
<src path="src"/>
</javac>
</target>
<target name="make-jar" depends="build">
<mkdir dir="jars"/>
<jar destfile="jars/simulator.jar" basedir="bin">
<manifest>
<attribute name="Main-Class" value="main.Main"/>
</manifest>
</jar>
</target>
</project>

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,40 @@
.data
a:
40
20
50
60
80
30
10
70
n:
8
.text
main:
sub %x3, %x3, %x3
sub %x4, %x4, %x4
load %x0, $n, %x8
outerloop:
blt %x3, %x8, innerloop
end
addi %x3, 1, %x4
innerloop:
addi %x3, 1, %x4
innerloopz:
blt %x4, %x8, swap
addi %3, 1, %x3
jmp outerloop
swap:
load %x3, $a, %x5
load %x4, $a, %x6
blt %x5, %x6, exchange
addi %x4, 1, %x4
jmp innerloopz
exchange:
sub %x7, %x7, %x7
add %x0, %x5, %x7
store %x6, 0, %x3
store %x7, 0, %x4
addi %x4, 1, %x4
jmp innerloopz

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1 @@
Hash of the Processor State = 255541867

View File

@ -0,0 +1,15 @@
.data
n:
11
.text
main:
load %x0, $n, %x3
divi %x3, 2, %x3
beq %x0, %x31, even
sub %x10, %x10, %x10
addi %x10, 1, %x10
end
even:
sub %x10, $x10, %x10
subi %x10, 1, %x10
end

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1 @@
Hash of the Processor State = -224294686

Binary file not shown.

View File

@ -0,0 +1,28 @@
.data
n:
10
.text
main:
addi %x0, 0, %x3
addi %x0, 1, %x4
add %x3, %x4, %x5
load %x0, $n, %x6
addi %x0, 65535, %x7
addi %x0, 0, %x8
store %x3, 0, %x7
subi %x7, 1, %x7
addi %x8, 1, %x8
store %x4, 0, %x7
subi %x7, 1, %x7
addi %x8, 1, %x8
for:
blt %x8, %x6, loop
end
loop:
add %x3, %x4, %x5
store %x5, 0, %x7
subi %x7, 1, %x7
addi %x8, 1, %x8
add %x0, %x4, %x3
add %x0, %x5, %x4
jmp for

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1 @@
Hash of the Processor State = -1518357572

Binary file not shown.

View File

@ -0,0 +1,23 @@
.data
a:
4567654
.text
main:
load %x0, $a, %x3
sub %x7, %x7, %x7
loop:
divi %x3, 10, %x4
addi %x31, 0, %x30
muli %x7, 10, %x7
add %x7, %x30, %x7
divi %x3, 10, %x3
bgt %x3, %x0, loop
load %x0, $a, %x5
beq %x5, %x7, palindrome
sub %x10, %x10, %x10
subi %x10, 1, %x10
end
palindrome:
sub %x10, %x10, %x10
addi %x10, 1, %x10
end

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,2 @@
Hash of the Processor State = 155317940

View File

@ -0,0 +1,24 @@
.data
a:
11
.text
main:
load %x0, $a, %x3
sub %x4, %x4, %x4
divi %x3, 2, %x4
sub %x6, %x6, %x6
addi %x6, 2, %x6
for:
bgt %x6, %x4, prime
div %x3, %x6, %x7
beq %x0, %x31, notprime
addi %x6, 1, %x6
jmp for
prime:
sub %x10, %x10, %x10
addi %x10, 1, %x10
end
notprime:
sub %x10, %x10, %x10
subi %x10, 1, %x10
end

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1 @@
Hash of the Processor State = -1414219998

Binary file not shown.

View File

@ -0,0 +1,92 @@
#!/bin/python
import sys
import os
import zipfile
import shutil
import subprocess
from threading import Timer
zip_file = sys.argv[1]
l = len(zip_file.split("/"))
print "Students :"
for i in range(0, len(zip_file.split("/")[l-1].split("_"))):
print zip_file.split("/")[l-1].split("_")[i].split(".")[0]
print ""
submissions_temp_dir = "./submissions/"
if not os.path.exists(submissions_temp_dir):
os.mkdir(submissions_temp_dir)
zip_ref = zipfile.ZipFile(zip_file, 'r')
zip_ref.extractall(submissions_temp_dir)
zip_ref.close()
shutil.copyfile("build.xml", submissions_temp_dir + "/build.xml")
os.chdir(submissions_temp_dir)
stdout_file = open("./tmp.output", 'a')
popen_args = ["ant", "make-jar"]
proc = subprocess.Popen(popen_args, stdout = stdout_file, stderr = stdout_file)
timer = Timer(5, proc.kill)
try:
timer.start()
stdout, stderr = proc.communicate()
finally:
timer.cancel()
stdout_file.close()
if not os.path.exists("jars/simulator.jar"):
print "compilation failed. jar file not created"
sys.exit(0)
test_cases_dir = "../test_cases"
total_marks = 0
scored_marks = 0
for testcase in os.listdir(test_cases_dir):
if ".out" in testcase:
total_marks = total_marks + 1
stdout_file = open("./" + testcase.split(".")[0] + ".observedoutput", 'w')
popen_args = ["java", "-Xmx1g", "-jar", "jars/simulator.jar", "./src/configuration/config.xml", "./" + testcase.split(".")[0] + ".observedstat", test_cases_dir + "/" + testcase]
# print popen_args
proc = subprocess.Popen(popen_args, stdout = stdout_file, stderr = stdout_file)
timer = Timer(5, proc.kill)
try:
timer.start()
stdout, stderr = proc.communicate()
finally:
timer.cancel()
stdout_file.close()
if os.path.exists("./" + testcase.split(".")[0] + ".observedoutput"):
expectedoutput_file = open(test_cases_dir + "/" + testcase.split(".")[0] + ".expected")
expected_hash = expectedoutput_file.readline()
expectedoutput_file.close()
correct = False
observedoutput_file = open("./" + testcase.split(".")[0] + ".observedoutput")
for line in observedoutput_file:
# if "Hash" in line:
# print "computed = " + line
# print "expected = " + expected_hash
if line == expected_hash:
correct = True
break
observedoutput_file.close()
if correct == True:
scored_marks = scored_marks + 1
print testcase + " : PASS!"
else:
print testcase + " : fail - incorrect hash"
else:
print testcase + " : fail - standard output file not created"
os.chdir("..")
shutil.rmtree(submissions_temp_dir)
print "\ntotal score = " + str(scored_marks) + " out of " + str(total_marks)