5f10626fa234d92b2e092c26f779bae5bcdd58f1
[fleet.git] / src / edu / berkeley / fleet / interpreter / Interpreter.java
1 package edu.berkeley.fleet.interpreter;
2 import java.io.*;
3 import java.util.*;
4 import java.util.concurrent.*;
5 import java.lang.reflect.*;
6 import edu.berkeley.sbp.util.ANSI;
7 import edu.berkeley.fleet.api.*;
8 import edu.berkeley.fleet.two.*;
9 import edu.berkeley.fleet.assembler.*;
10 import edu.berkeley.fleet.util.*;
11
12 public class Interpreter extends FleetTwoFleet {
13
14     /** used to allocate serial numbers; see InterpreterDestination for further detail */
15     int maxAllocatedDestinationSerialNumber = 0;
16
17     private InterpreterShip debugShip = null;
18     private BlockingQueue<BitVector> debugStream = new LinkedBlockingQueue<BitVector>();
19     private LinkedHashMap<String,InterpreterShip> ships = new LinkedHashMap<String,InterpreterShip>();
20     public Iterator<Ship> iterator() { return (Iterator<Ship>)(Object)ships.values().iterator(); }
21     public Ship getShip(String type, int ordinal) {
22         for(Ship s : this)
23             if (s.getType().equals(type))
24                 if (ordinal-- <= 0)
25                     return s;
26         return null;
27     }
28
29     /** do not use this; it is going to go away */
30     public Interpreter() { this(true); }
31     public Interpreter(boolean logging) {
32         this(new String[] {
33                 "Debug",
34                 "Memory",
35                 "Memory",
36                 "Memory",
37                 "Alu",
38                 "Alu",
39                 "Alu",
40                 "Alu",
41                 "Alu",
42                 "Alu",
43                 "Alu",
44                 "Fifo",
45                 "Fifo",
46                 "Counter",
47                 "Counter",
48                 "Counter",
49                 "Counter",
50                 "Counter",
51                 "Counter",
52                 "Counter",
53                 "Counter",
54                 "Counter",
55                 "Counter",
56                 "Counter",
57                 "Counter",
58                 "Counter",
59                 "Counter",
60                 "Lut3",
61                 "CarrySaveAdder",
62                 "Rotator",
63                 "Timer",
64             }, logging);
65     }
66
67     public Interpreter(String[] ships, boolean logging) {
68         int i=0;
69         Log.quiet = !logging;
70         for(String s : ships) {
71             createShip(ships[i], ships[i]+"_"+i);
72             i++;
73         }
74     }
75
76     private Ship createShip(String shipType, String shipname) {
77         try {
78             if (ships.get(shipname)!=null) return ships.get(shipname);
79             Class c = Class.forName("edu.berkeley.fleet.interpreter."+shipType);
80             Constructor con = c.getConstructor(new Class[] { Interpreter.class, String.class, ShipDescription.class });
81             String src = "/ships/" + shipType + ".ship";
82             InputStream is = getClass().getResourceAsStream(src);
83             BufferedReader br = new BufferedReader(new InputStreamReader(is));
84             ShipDescription sd = new ShipDescription(this, shipType, br);
85             InterpreterShip ret = (InterpreterShip)con.newInstance(new Object[] { this, shipname, sd });
86             ships.put(shipname, ret);
87             if (shipType.equals("Debug") && debugShip == null)
88                 debugShip = ret;
89             return ret;
90         } catch (Exception e) {
91             e.printStackTrace();
92             return null;
93         }
94     }
95
96     void debug(long d) { debug(new BitVector(getWordWidth()).set(d)); }
97     void debug(BitVector data) {
98         try {
99             if (debugStream != null) debugStream.put(data);
100             else Log.println(ANSI.invert("   DEBUG: got a datum: " +  data+ANSI.clreol()));
101         } catch (Exception e) {
102             throw new RuntimeException(e);
103         }
104     }
105
106     // Instruction Encoding /////////////////////////////////////////////////////////////////////////
107
108     public BitVector getDestAddr(Path path) {
109         long ret = ((InterpreterDestination)path.getDestination()).getSerialNumber();
110         BitVector sig = path.getSignal();
111         BitVector bv = new BitVector(DISPATCH_PATH.valmaskwidth+1);
112         bv.set(ret);
113         if (sig != null) {
114             if (sig.length() > 1) throw new RuntimeException("signal was " + sig.length() + " bits long!");
115             if (sig.length() > 0 && sig.get(0)) bv.set(bv.length()-1,true);
116         }
117         return bv;
118     }
119
120
121     // ShipDescription //////////////////////////////////////////////////////////////////////////////
122
123     public void expand(ShipDescription sd) {
124         try {
125             String filename = sd.getName();
126             //String filename = (sd.getName().charAt(0)+"").toUpperCase() + sd.getName().substring(1).toLowerCase();
127             File outf = new File("build/java/edu/berkeley/fleet/interpreter/"+filename+".java");
128             new File(outf.getParent()).mkdirs();
129             System.err.println("writing to " + outf);
130             FileOutputStream out = new FileOutputStream(outf);
131             PrintWriter pw = new PrintWriter(out);
132
133             pw.println("package edu.berkeley.fleet.interpreter;");
134             pw.println("import edu.berkeley.sbp.util.ANSI;");
135             pw.println("import edu.berkeley.fleet.api.*;");
136             pw.println("import edu.berkeley.fleet.two.*;");
137             pw.println("import edu.berkeley.fleet.*;");
138             pw.println("import java.util.*;");
139             pw.println("import java.io.*;");
140             pw.println("");
141             pw.println("public class "+filename+" extends InterpreterShip {");
142             pw.println("");
143             pw.println("    public "+filename+"(Interpreter fleet, String name, ShipDescription sd) {");
144             pw.println("       super(fleet, sd);");
145             pw.println("    }");
146             pw.println("");
147             for(DockDescription b : sd) {
148                 String name = b.getName();
149                 pw.print("    InterpreterDock box_");
150                 pw.print(name);
151                 pw.print(" = new InterpreterDock(this, shipDescription.getDockDescription(\""+name+"\"));");
152             }
153             pw.println("");
154             pw.println(sd.getSection("fleeterpreter"));
155             pw.println("}");
156             pw.flush();
157             pw.close();
158         } catch (Exception e) { throw new RuntimeException(e); }
159     }
160
161     // Run //////////////////////////////////////////////////////////////////////////////
162
163     public FleetProcess run(final Instruction[] instructions) {
164         InterpreterProcess ip = initialize(instructions);
165         Thread ipt = new Thread(ip);
166         ipt.setDaemon(true);
167         ipt.start();
168         return ip;
169     }
170
171     public InterpreterProcess initialize(Instruction[] instr) {
172         return new InterpreterProcess(instr);
173     }
174
175     public class InterpreterProcess extends FleetProcess implements Runnable {
176         private Instruction[] instructions;
177         public synchronized void sendWord(Destination d, BitVector word) { sendWord(d, word, null); }
178         public synchronized void sendWord(Destination d, BitVector word, BitVector signal) {
179             InterpreterPath path = (InterpreterPath)debugShip.getDock("in").getPath(d, signal==null?new BitVector(1):signal);
180             new Packet(path, word, false).send();
181         }
182         public synchronized void sendToken(Destination d) {
183             InterpreterPath path = (InterpreterPath)debugShip.getDock("in").getPath(d, new BitVector(1));
184             new Packet(path, new BitVector(getWordWidth()), true).send();
185         }
186         public InterpreterProcess(Instruction[] instructions) {
187             this.instructions = instructions;
188             for(Instruction i : instructions)
189                 sendInstruction(i);
190         }
191         public Fleet getFleet() { return Interpreter.this; }
192         public synchronized void sendInstruction(Instruction i) {
193             long il = writeInstruction(i, debugShip.getDock("in"));
194             Path path = debugShip.getDock("in").getPath(i.dock.getInstructionDestination(), null);
195             new Packet((InterpreterPath)path, new BitVector(getWordWidth()).set(il), false).send();
196         }
197         public Dock getDebugInputDock() { return debugShip.getDock("in"); }
198         public BitVector recvWord() {
199             try {
200                 return debugStream.take();
201             } catch (Exception e) { throw new RuntimeException(e); }
202         }
203         protected void _terminate() { }
204         public void run() {
205             try {
206                 while(!isTerminated()) {
207                     flush();
208                 }
209                 for(InterpreterShip ship : ships.values())
210                     ship.reset();
211                 debugStream.clear();
212             } catch (Exception e) {
213                 if (isTerminated()) return;
214                 throw new RuntimeException(e);
215             }
216         }
217
218         public void flush() {
219             // FIXME: should this run until we detect some sort of "quiescence"?  OTOH that might never happen.
220             for(InterpreterShip ship : ships.values())
221                 for(int j=0; j<10; j++)
222                     if (!isTerminated())
223                         synchronized(this) {
224                             ship._service();
225                         }
226         }
227
228         public synchronized void step(Dock d) {
229             ((InterpreterDock)d).service();
230         }
231         
232         public synchronized void step(Ship s) {
233             ((InterpreterShip)s).service();
234         }
235
236     }
237 }