87c96d8fffa19328815fb75c71abf0256cc648e4
[fleet.git] / src / edu / berkeley / fleet / interpreter / Interpreter.java
1 package edu.berkeley.fleet.interpreter;
2 import edu.berkeley.fleet.api.*;
3
4 import edu.berkeley.fleet.api.*;
5 import edu.berkeley.fleet.*;
6 import java.lang.reflect.*;
7 import edu.berkeley.sbp.chr.*;
8 import edu.berkeley.sbp.misc.*;
9 import edu.berkeley.sbp.meta.*;
10 import edu.berkeley.sbp.bind.*;
11 import edu.berkeley.sbp.util.*;
12 import java.util.*;
13 import java.io.*;
14 import edu.berkeley.fleet.ships.*;
15
16 public class Interpreter extends Fleet implements Iterable<Ship> {
17
18     public InterpreterBenkoBox resolve(edu.berkeley.fleet.api.BenkoBox bb) { return (InterpreterBenkoBox)bb; }
19
20     public void dumpCode(Instruction[] instructions) throws IOException {
21         DataOutputStream dos = new DataOutputStream(new FileOutputStream("build/fleet.bin"));
22         for(int i=1; i<instructions.length; i++) {
23             Instruction inst = instructions[i];
24             writeInstruction(dos, inst);
25         }
26         dos.flush();
27         dos.close();
28     }
29
30     public void dispatch(Instruction i, long address) {
31
32         if (i instanceof Instruction.Executable) {
33             InterpreterBenkoBox sourceBenkoBox = resolve(((Instruction.Executable)i).benkoBox);
34             if (!(sourceBenkoBox instanceof InstructionPort))
35                 throw new RuntimeException(sourceBenkoBox + " is not an InstructionPort!");
36             ((InstructionPort)sourceBenkoBox).addInstruction(((Instruction.Executable)i));
37
38         } else if (i instanceof Instruction.Literal.CodeBagDescriptor) {
39             Log.dispatch(i);
40             Instruction.Literal.CodeBagDescriptor cbd = (Instruction.Literal.CodeBagDescriptor)i;
41             dispatchCodeBag(cbd.offset+address, cbd.size);
42             
43         } else if (i instanceof Instruction.Literal.Absolute) {
44             InterpreterBenkoBox destBenkoBox = resolve(((Instruction.Literal.Absolute)i).dest);
45             Log.data(((Instruction.Literal.Absolute)i).value+"", null, destBenkoBox);
46             destBenkoBox.addDataFromFabric((int)((Instruction.Literal.Absolute)i).value);
47
48         } else if (i instanceof Instruction.Kill) {
49             InterpreterBenkoBox benkoBox = resolve(((Instruction.Kill)i).benkoBox);
50             if (!(benkoBox instanceof InstructionPort))
51                 throw new RuntimeException(benkoBox + " is not an InstructionPort!");
52             ((InstructionPort)benkoBox).kill(((Instruction.Kill)i).count);
53
54         } else {
55             throw new Error("unsupported: " + i.getClass().getName());
56         }
57     }
58
59     /** some "halt ship" can turn this on to stop the interpreter */
60     public boolean halt = false;
61
62     public int[] mem = new int[0];
63
64     public Instruction[] instructions = null;
65     public ArrayList<String> imports = new ArrayList<String>();
66
67     private static String getUniqueName(Ship ship) {
68         return ship.getType() + ship.getOrdinal();
69     }
70
71     public ArrayList<InterpreterShip> shiplist = new ArrayList<InterpreterShip>();
72     public HashMap<String,InterpreterShip> ships = new HashMap<String,InterpreterShip>();
73
74     /** read a machine-formatted instruction from a file (into a Java object) */
75     public Instruction readInstruction(DataInputStream is) throws IOException {
76         // FIXME
77         return null;
78     }
79
80     public void writeInstruction(DataOutputStream os, Instruction d) throws IOException {
81         long instr = 0;
82
83         // Kill is encoded as Execute with the illegal combination (Latch & ~DataIn)
84         if (d instanceof Instruction.Kill) {
85             Instruction.Kill k = (Instruction.Kill)d;
86             d = new Instruction.Executable(k.benkoBox, null, k.count, false, false, true, false, false, false);
87         }
88
89         if (d instanceof Instruction.Executable) {
90             Instruction.Executable inst = (Instruction.Executable)d;
91             InterpreterBenkoBox dest = resolve(inst.dest);
92             instr = dest==null ? 0 : (dest.addr << 1);
93             instr |= (((long)inst.count) << (11+1));
94             if (inst.tokenIn)  instr |= (1L << (11+1+7+0));
95             if (inst.dataIn)   instr |= (1L << (11+1+7+1));
96             if (inst.latch)    instr |= (1L << (11+1+7+2));
97             if (inst.dataOut)  instr |= (1L << (11+1+7+3));
98             if (inst.tokenOut) instr |= (1L << (11+1+7+4));
99             instr |= ((long)resolve(inst.benkoBox).instr_addr) << (11+5+7+1);
100
101         } else if (d instanceof Instruction.Literal.Absolute) {
102             Instruction.Literal.Absolute ld = (Instruction.Literal.Absolute)d;
103             instr = (2L << (11+24));
104             instr |= (resolve(ld.dest).addr) << 24;
105             instr |= ((long)ld.value);
106         }
107
108         dump(os, (instr >> (5*8)) & 0xff);
109         dump(os, (instr >> (4*8)) & 0xff);
110         dump(os, (instr >> (3*8)) & 0xff);
111         dump(os, (instr >> (2*8)) & 0xff);
112         dump(os, (instr >> (1*8)) & 0xff);
113         dump(os, (instr >> (0*8)) & 0xff);
114     }
115     public void dump(OutputStream os, long data_) throws IOException {
116         int data = (int)data_;
117         os.write((byte)data);
118         System.out.println(data);
119     }
120
121     public Iterator<Ship> iterator() {
122         return (Iterator<Ship>)(Object)shiplist.iterator();
123     }
124
125     public void dispatchCodeBag(long base, long size) {
126         for(long i=base; i<base+size; i++)
127             dispatch(instructions[(int)i], i);
128     }
129
130     public void go() {
131         Instruction.Literal.CodeBagDescriptor cbl =
132             (Instruction.Literal.CodeBagDescriptor)instructions[0];
133         dispatchCodeBag(cbl.offset+0, cbl.size);
134
135         while(!halt)
136             for(InterpreterShip ship : ships.values())
137                 for(int j=0; j<10; j++)
138                     ship._service();
139
140         // run the ships a bit longer for good measure
141         for(int i=0; i<100; i++)
142             for(InterpreterShip ship : ships.values())
143                 for(int j=0; j<10; j++)
144                     ship._service();
145
146         // check the state of the ships
147         for(InterpreterShip ship : ships.values())
148             ship.shutdown();
149
150         Log.println(Log.yellow("    DONE: ====== FLEET is halted.  Have a nice day.  ======"));
151     }
152
153     public void dumpMem() {
154         Log.print(Log.cyan("  MEMORY: "));
155         for(int i=0; i<mem.length; i++) {
156             if ((i%10)==0 && i!=0) Log.print(Log.cyan("          "));
157             Log.print(Log.cyan(mem[i] + " "));
158             if ((i%10)==9 && i!=mem.length-1) Log.println("");
159         }
160         Log.println();
161     }
162
163     public void writeMem(int addr, int data) {
164         if (addr >= mem.length) {
165             int[] mem2 = new int[addr*2+1];
166             System.arraycopy(mem, 0, mem2, 0, mem2.length);
167             mem = mem2;
168         }
169         mem[addr] = data;
170     }
171
172     public InterpreterShip getShip(String name) {
173         InterpreterShip s = ships.get(name);
174         if (s == null) throw new RuntimeException("unknown ship \""+name+"\"");
175         return s;
176     }
177
178     public InterpreterShip tryCreate(String classname, String shipname) {
179         try {
180             Class c = Class.forName(classname);
181             Constructor con = c.getConstructor(new Class[] { Interpreter.class, String.class });
182             InterpreterShip ret = (InterpreterShip)con.newInstance(new Object[] { this, shipname });
183             ships.put(shipname, ret);
184             shiplist.add(ret);
185             return ret;
186         } catch (Exception e) {
187             return null;
188         }
189     }
190
191     public void sendToken(InterpreterBenkoBox source, InterpreterBenkoBox dest) {
192         Log.token(source, dest);
193         dest.addTokenFromFabric();
194     }
195
196     public void sendData(InterpreterBenkoBox source, int data, InterpreterBenkoBox dest) {
197         Log.data(data+"", source, dest);
198         dest.addDataFromFabric(data);
199     }
200
201     public void dumpFabric(boolean quiet) {
202         // FIXME: this is really ugly: the order of port declarations in
203         //        the XXXShip.java file must match the order in the .balsa file!
204
205         ArrayList instructionports = new ArrayList<InterpreterBenkoBox>();
206         for(InterpreterShip ship : shiplist)
207             for(BenkoBox port : ship.getBenkoBoxes())
208                 if (!((InterpreterBenkoBox)port).special())
209                     instructionports.add(port);
210         FabricTree instructions =
211             new FabricTree((InterpreterBenkoBox[])instructionports.toArray(new InterpreterBenkoBox[0]),
212                            "ihorn",
213                            "instruction");
214
215         ArrayList inputports = new ArrayList<InterpreterBenkoBox>();
216         for(InterpreterShip ship : shiplist)
217             for(BenkoBox port : ship.getBenkoBoxes())
218                 if (!((InterpreterBenkoBox)port).special())
219                     inputports.add(port);
220         FabricTree inputs =
221             new FabricTree((InterpreterBenkoBox[])inputports.toArray(new InterpreterBenkoBox[0]),
222                            "horn",
223                            "dest");
224
225         ArrayList outputports = new ArrayList<InterpreterBenkoBox>();
226         for(InterpreterShip ship : shiplist)
227             for(BenkoBox port : ship.getBenkoBoxes())
228                 if (!((InterpreterBenkoBox)port).special())
229                     outputports.add(port);
230         FabricTree outputs =
231             new FabricTree((InterpreterBenkoBox[])outputports.toArray(new InterpreterBenkoBox[0]),
232                            "funnel",
233                            "source");
234
235         if (quiet) return;
236         System.out.println("`include \"macros.v\"");
237         /*
238           HashSet<Class> added = new HashSet<Class>();
239           for(Ship ship : shiplist)
240           if (!added.contains(ship.getClass())) {
241           added.add(ship.getClass());
242           System.out.println("import ["+ship.getBalsaName()+"]");
243           }
244         */
245         System.out.println("module fabric(clk, data_Execute0_in_r, data_Execute0_in_a, data_Execute0_in,");
246         System.out.println("                   data_Debug0_out_r, data_Debug0_out_a, data_Debug0_out);");
247         System.out.println("  input  clk;");
248         System.out.println("  input  data_Execute0_in_r;");
249         System.out.println("  output data_Execute0_in_a;");
250         System.out.println("  input  [(`PACKET_WIDTH-1):0] data_Execute0_in;");
251         System.out.println("  output data_Debug0_out_r;");
252         System.out.println("  input  data_Debug0_out_a;");
253         System.out.println("  output [(`PACKET_WIDTH-1):0] data_Debug0_out;");
254         System.out.println("  wire   [(`INSTRUCTION_WIDTH-1):0] data_Execute0_ihorn;");
255         System.out.println("  wire   [(`PACKET_WIDTH-1):0] data_Execute0_dhorn;");
256         System.out.println();
257         
258         System.out.println();
259
260         instructions.dumpChannels(true);
261         outputs.dumpChannels(true);
262         inputs.dumpChannels(true);
263         for(InterpreterShip ship : shiplist)
264             for(BenkoBox port : ship.getBenkoBoxes()) {
265                 if (ship instanceof Execute && port instanceof Outbox) continue;
266                 System.out.println("  wire [(`PACKET_WIDTH-1):0] data_"+getUniqueName(ship)+"_"+port.getName()+";");
267             }
268
269         System.out.println("");
270         instructions.dumpChannels(false);
271         System.out.println("");
272         outputs.dumpChannels(false);
273         System.out.println("");
274         inputs.dumpChannels(false);
275         System.out.println("");
276         for(InterpreterShip ship : shiplist) {
277             System.out.print(ship.getClass().getSimpleName().toLowerCase());
278             System.out.print(" ");
279             System.out.print("krunk"+(krunk++));
280             System.out.print("(clk, ");
281             boolean first = true;
282             for(BenkoBox port : ship.getBenkoBoxes()) {
283                 if (!first) System.out.print(", ");
284                 first = false;
285                 System.out.print("data_"+getUniqueName(port.getShip())+"_"+port.getName()+"_r, ");
286                 System.out.print("data_"+getUniqueName(port.getShip())+"_"+port.getName()+"_a, ");
287                 System.out.print("data_"+getUniqueName(port.getShip())+"_"+port.getName());
288                 System.out.print(" ");
289             }
290             System.out.println(");");
291
292             for(BenkoBox port : ship.getBenkoBoxes()) {
293                 if (((InterpreterBenkoBox)port).special()) continue;
294                 if (port instanceof Inbox) {
295                     if (((InterpreterBenkoBox)port).noInbox())
296                         System.out.print("stupidinbox");
297                     else
298                         System.out.print("inbox");
299                 } else {
300                     System.out.print("outbox");
301                 }
302                 System.out.print(" krunk"+(krunk++)+"(clk, ");
303                 System.out.print("instruction_"+getUniqueName(port.getShip())+"_"+port.getName()+"_r, ");
304                 System.out.print("instruction_"+getUniqueName(port.getShip())+"_"+port.getName()+"_a, ");
305                 System.out.print("instruction_"+getUniqueName(port.getShip())+"_"+port.getName()+", ");
306                 System.out.print("dest_"+getUniqueName(port.getShip())+"_"+port.getName()+"_r, ");
307                 System.out.print("dest_"+getUniqueName(port.getShip())+"_"+port.getName()+"_a, ");
308                 System.out.print("dest_"+getUniqueName(port.getShip())+"_"+port.getName()+", ");
309                 System.out.print("source_"+getUniqueName(port.getShip())+"_"+port.getName()+"_r, ");
310                 System.out.print("source_"+getUniqueName(port.getShip())+"_"+port.getName()+"_a, ");
311                 System.out.print("source_"+getUniqueName(port.getShip())+"_"+port.getName()+", ");
312                 System.out.print("data_"+getUniqueName(port.getShip())+"_"+port.getName()+"_r, ");
313                 System.out.print("data_"+getUniqueName(port.getShip())+"_"+port.getName()+"_a, ");
314                 System.out.print("data_"+getUniqueName(port.getShip())+"_"+port.getName());
315                 System.out.print(");");
316                 System.out.println();
317             }
318
319         }
320         System.out.println("funnel topfun(clk,"+
321                            "              dest_r, dest_a, dest,"+
322                            "              source_r, source_a, source,"+
323                            "              data_Execute0_dhorn_r, data_Execute0_dhorn_a, data_Execute0_dhorn);");
324         System.out.println("assign instruction_r = data_Execute0_ihorn_r;");
325         System.out.println("assign data_Execute0_ihorn_a = instruction_a;");
326         System.out.println("assign instruction = data_Execute0_ihorn;");
327         System.out.println("endmodule");
328     }
329
330     private static class FabricTree {
331         int master_idx = 1;
332         String prefix;
333         Node root;
334         public void dumpChannels(boolean decl) { root.dumpChannels(0, decl); }
335         public FabricTree(InterpreterBenkoBox[] ports, String component, String prefix) {
336             this.prefix = prefix;
337             root = (Node)mkNode("", component, ports, 0, ports.length, 0, 0);
338         }
339         private Object mkNode(String name, String component, InterpreterBenkoBox[] ports,
340                               int start, int end, int addr, int bits) {
341             if (end-start == 0) return null;
342             if (end-start == 1) {
343                 InterpreterBenkoBox p = ports[start];
344                 if (prefix.equals("instruction")) {
345                     p.instr_addr = addr;
346                     p.instr_bits = bits;
347                 } else {
348                     p.addr = addr;
349                     p.bits = bits;
350                 }
351                 return p;
352             }
353             int len = end-start;
354             return new Node(name,
355                             component,
356                             mkNode(name+"_0", component, ports, start, start+len/2, addr, bits+1),
357                             mkNode(name+"_1", component, ports, start+len/2, end,   addr | (1 << bits), bits+1),
358                             addr,
359                             bits);
360         }
361         private String describe(String prefix, Object o) {
362             if (o==null) return null;
363             if (o instanceof InterpreterBenkoBox) {
364                 InterpreterBenkoBox p = (InterpreterBenkoBox)o;
365                 return prefix+"_"+getUniqueName(p.getShip())+"_"+p.getName();
366             }
367             if (o instanceof Node) {
368                 return ((Node)o).describe(prefix);
369             }
370             return null;
371         }
372         private class Node {
373             Object left;
374             Object right;
375             String name;
376             String component;
377             int addr;
378             int bits;
379             public Node(String name, String component, Object left, Object right, int addr, int bits) {
380                 this.left = left;
381                 this.right = right;
382                 this.name = name;
383                 this.component = component;
384                 this.addr = addr;
385                 this.bits = bits;
386             }
387             public void dumpChannels(int indentamount, boolean decl) {
388                 String indent = "";
389                 for(int i=0; i<indentamount; i++) indent += "  ";
390                 if (decl) {
391                     String n = describe(prefix).startsWith("instruction")
392                         ? "[(`INSTRUCTION_WIDTH-1):0]" : "[(`PACKET_WIDTH-1):0]";
393                     System.out.println("  wire "+n+" "+indent+describe(prefix)+";");
394                 } else {
395                     System.out.println("     "+indent+
396                                        component+" "+
397                                        "krunk"+(krunk++)+"(clk, "+
398                                        describe(prefix)+"_r, "+
399                                        describe(prefix)+"_a, "+
400                                        describe(prefix)+", "+
401                                        FabricTree.this.describe(prefix, left)+"_r, "+
402                                        FabricTree.this.describe(prefix, left)+"_a, "+
403                                        FabricTree.this.describe(prefix, left)+", "+
404                                        FabricTree.this.describe(prefix, right)+"_r, "+
405                                        FabricTree.this.describe(prefix, right)+"_a, "+
406                                        FabricTree.this.describe(prefix, right)+
407                                        ");");
408                 }
409                 dumpChannels(left, indentamount+1, decl);
410                 dumpChannels(right, indentamount+1, decl);
411             }
412             public void dumpChannels(Object o, int indentamount, boolean decl) {
413                 if (o==null) return;
414                 if (o instanceof Node) {
415                     ((Node)o).dumpChannels(indentamount, decl);
416                 } else {
417                     String indent = "";
418                     for(int i=0; i<indentamount; i++) indent += "  ";
419                     if (decl) {
420                         String n = FabricTree.this.describe(prefix,o).startsWith("instruction")
421                             ? "[(`INSTRUCTION_WIDTH-1):0]" : "[(`PACKET_WIDTH-1):0]";
422                         System.out.println("  wire "+n+" "+indent+FabricTree.this.describe(prefix,o)+";");
423                     }
424                 }
425             }
426             public String describe(String prefix) {
427                 return prefix+name;
428             }
429         }
430     }
431     public static int krunk=0;
432
433     public int computeOffset(int origin, int target) { return target - origin; }
434     public int computeTarget(int origin, int offset) { return origin + offset; }
435 }