1 package edu.berkeley.fleet.assembler;
2 import edu.berkeley.fleet.api.*;
3 import edu.berkeley.sbp.*;
4 import edu.berkeley.sbp.chr.*;
5 import edu.berkeley.sbp.misc.*;
6 import edu.berkeley.sbp.meta.*;
7 import edu.berkeley.sbp.util.*;
8 import static edu.berkeley.fleet.util.BitManipulations.*;
9 import edu.berkeley.fleet.two.*;
10 import edu.berkeley.fleet.api.Instruction.Set;
11 import static edu.berkeley.fleet.api.Instruction.*;
12 import static edu.berkeley.fleet.api.Instruction.Set.*;
13 import static edu.berkeley.fleet.api.Predicate.*;
14 import edu.berkeley.fleet.two.*;
15 import edu.berkeley.fleet.fpga.*;
16 import edu.berkeley.fleet.interpreter.*;
22 * @author Adam Megacz <megacz@cs.berkeley.edu>
26 private static final BitVector SIGNAL_ZERO = new BitVector(1);
27 private static final BitVector SIGNAL_ONE = new BitVector(1);
29 SIGNAL_ONE.set(0,true);
33 expect = new ArrayList<Long>();
37 //////////////////////////////////////////////////////////////////////////////
40 private ArrayList<String> imports = new ArrayList<String>();
42 private HashMap<String,Ship> shipMap = new HashMap<String,Ship>();
44 // codebags in numerical order
45 private ArrayList<CodeBag> codeBags = new ArrayList<CodeBag>();
46 private HashMap<String,CodeBag> codeBagsByName = new HashMap<String,CodeBag>();
48 private CodeBag getCodeBag(String name) {
49 CodeBag cb = codeBagsByName.get(name);
50 if (cb!=null) return cb;
51 return new CodeBag(name);
54 private static Union grammar;
55 private static synchronized Union getGrammar() throws Exception {
56 if (grammar != null) return grammar;
57 InputStream grammarStream =
58 Parser.class.getClassLoader().getResourceAsStream("edu/berkeley/fleet/assembler/fleet.g");
59 CharParser metaGrammarParser = new CharParser(GrammarAST.getMetaGrammar());
60 Tree<String> parsedGrammar = metaGrammarParser.parse(new CharInput(grammarStream)).expand1();
61 grammar = GrammarAST.buildFromAST(parsedGrammar, "s", new GrammarAST.ImportResolver() {
62 public InputStream getImportStream(String importname) { return null; }
67 // FIXME: this ought to be cached via serialization, I think
68 private static CharParser cp = null;
69 Tree<String> parseIt(Reader r) throws Exception {
71 cp = new CharParser(getGrammar());
72 CharInput ci = new CharInput(r);
73 Forest f = cp.parse(ci);
77 public Instruction[] parse(Reader r) throws Exception {
78 // this needs to be "code bag zero"
79 CodeBag baseCodeBag = new CodeBag();
80 CodeBag rootCodeBag = new CodeBag();
83 if (fleet instanceof Fpga) {
84 dock = ((Fpga)fleet).getUniversalSource();
86 dock = ((Interpreter)fleet).getUniversalSource();
88 //baseCodeBag.add(new Set(dock, false, IgnoreOLC, SetDest.DataLatch, (rootCodeBag.getFakeAddress())), true);
89 Tree<String> parsed = (Tree<String>)parseIt(r);
90 walk(parsed, rootCodeBag);
92 // map from arbitrary identifiers to actual addresses
93 int[] codeBagMap = new int[codeBags.size()];
95 for(int i=0; i<codeBags.size(); i++) {
96 CodeBag c = codeBags.get(i);
97 codeBagMap[i] = count;
98 for(Instruction inst : c) {
103 // now write for real
105 ArrayList<Instruction> ret = new ArrayList<Instruction>();
106 for(int i=0; i<codeBags.size(); i++) {
107 CodeBag c = codeBags.get(i);
108 for(int j=0; j<c.size(); j++) {
109 Instruction inst = c.get(j);
110 if (c.isCBD.contains(j)) {
113 lit = FleetTwoFleet.CBD_SIZE.setval(lit, codeBags.get((int)old.immediate).size());
114 lit = FleetTwoFleet.CBD_OFFSET.setval(lit, codeBagMap[(int)old.immediate]);
115 inst = new Set(old.dock, false, IgnoreOLC, SetDest.DataLatch, lit);
122 for(int i=0; i<codeBags.size(); i++) {
123 if (codeBags.get(i)==rootCodeBag) {
125 lit = FleetTwoFleet.CBD_SIZE.setval(lit, codeBags.get(i).size());
126 lit = FleetTwoFleet.CBD_OFFSET.setval(lit, codeBagMap[i]);
130 if (codeBags.size()<=2)
131 return (Instruction[])ret.toArray(new Instruction[0]);
132 return fixup((Instruction[])ret.toArray(new Instruction[0]), startcbd);
135 private Instruction[] fixup(Instruction[] instructions, long startcbd) {
136 ArrayList<Instruction> ret = new ArrayList<Instruction>();
140 if (fleet instanceof Fpga) {
141 us = ((Fpga)fleet).getUniversalSource();
143 us = ((Interpreter)fleet).getUniversalSource();
146 Dock inAddrWrite = null;
147 Dock inDataWrite = null;
153 for(Ship ship : fpga) {
154 if ("Memory".equals(ship.getType()) && ship.getOrdinal()==0) {
155 inAddrWrite = ship.getDock("inAddrWrite");
156 inDataWrite = ship.getDock("inDataWrite");
157 inCBD = ship.getDock("inCBD");
158 out = ship.getDock("out");
159 ihorn = ship.getDock("outIhorn");
161 if ("Debug".equals(ship.getType()) && ship.getOrdinal()==0) {
162 debugIn = ship.getDock("in");
166 for(int i=0; i<instructions.length; i++) {
167 Instruction inst = instructions[i];
170 long lit = ((Instruction.Set)inst).immediate;
171 long offset = (lit >> 6) & ~(-1L << 10);
172 long size = (lit >> 0) & ~(-1L << 6);
173 //startcbd = (offset << 6) | size;
179 long lit = ((Fpga)fpga).writeInstruction(instructions[i], us);
180 ret.add(discard(out));
181 ret.add(new Instruction.Shift(inDataWrite, false, IgnoreOLC, new BitVector(fpga.getWordWidth()).set(getField(36, 19, lit))));
182 ret.add(new Instruction.Shift(inDataWrite, false, IgnoreOLC, new BitVector(fpga.getWordWidth()).set(getField(18, 0, lit))));
183 ret.add(deliver(inDataWrite));
184 ret.add(new Instruction.Shift(inAddrWrite, false, IgnoreOLC, new BitVector(fpga.getWordWidth()).set(getField(36, 19, i))));
185 ret.add(new Instruction.Shift(inAddrWrite, false, IgnoreOLC, new BitVector(fpga.getWordWidth()).set(getField(18, 0, i))));
186 ret.add(deliver(inAddrWrite));
188 ret.add(new Instruction.Shift(inCBD, false, IgnoreOLC, new BitVector(fpga.getWordWidth()).set(getField(36, 19, startcbd))));
189 ret.add(new Instruction.Shift(inCBD, false, IgnoreOLC, new BitVector(fpga.getWordWidth()).set(getField(18, 0, startcbd))));
190 ret.add(wait(inCBD));
191 ret.add(deliver(inCBD));
192 ret.add(sendto(out, out.getPath(inCBD.getDataDestination(),null)));
193 ret.add(new Instruction.Set(ihorn, false, IgnoreOLC, SetDest.InnerLoopCounter, SetSource.Infinity));
194 ret.add(new Instruction.Move(ihorn, false, IgnoreOLC, false, null,false,true,true,true,true,false));
195 return (Instruction[])ret.toArray(new Instruction[0]);
198 /** in the first pass, codebags are assigned "addresses" in arbitrary order */
199 void walk(Tree<String> t, CodeBag cb) {
201 String head = t.head();
203 } else if (head.equals("Program")) {
204 for(Tree<String> tc : t.child(0))
207 for(Tree<String> statement : t.child(1))
208 fillCodeBag(statement, cb);
210 } else if (head.equals("#import")) {
213 } else if (head.equals("#ship")) {
214 String name = name(t.child(0));
215 String type = string(t.child(1));
218 if (fleet instanceof FleetWithDynamicShips) {
219 FleetWithDynamicShips dyn = ((FleetWithDynamicShips)fleet);
220 ship = dyn.createShip(type, name);
222 throw new RuntimeException("couldn't find a ship called \""+type+"\"");
224 ship = allocateShip(type);
226 shipMap.put(name, ship);
228 } else if (head.equals("#include")) {
230 walk(parseIt(new InputStreamReader(new FileInputStream(string(t.child(0))))), cb);
231 } catch (Exception e) {
232 throw new RuntimeException(e);
235 } else if (head.equals("#expect")) {
236 expect.add(number(t.child(0)));
237 } else if (head.equals("#skip")) {
243 String string(Tree<String> t) {
245 if (t.head() != null) ret += t.head();
246 for(Tree<String> c : t)
251 String stringBody(Tree<String> t) {
253 for(Tree<String> c : t)
258 String name(Tree<String> t) {
259 return string(t.child(0))+string(t.child(1));
262 Path path(Dock dock, Tree<String> t) {
263 if (!"Dock".equals(t.head()) && !"Destination".equals(t.head()) && !"ShipSpecificLiteral".equals(t.head())) return null;
265 String shipName = name(t.child(0));
266 String portName = name(t.child(1));
267 String subPort = t.size()<3 ? null : name(t.child(2));
268 Ship ship = shipMap.get(shipName);
269 if (ship==null) throw new RuntimeException("no such ship \""+shipName+"\"");
270 Destination ret = null;
273 if (b.getName().equals(portName)) {
277 throw new RuntimeException("no such pump \""+portName+"\"");
278 if (subPort==null) subPort="";
279 if (":i".equals(t.head())) return dock.getPath(bb.getInstructionDestination(),SIGNAL_ZERO);
280 if (":1".equals(t.head())) return dock.getPath(bb.getDataDestination(),SIGNAL_ONE);
281 if (":0".equals(t.head())) return dock.getPath(bb.getDataDestination(),SIGNAL_ZERO);
282 return dock.getPath(bb.getDataDestination(),SIGNAL_ZERO);
285 Dock dock(Tree<String> t) {
286 if (!"Dock".equals(t.head()) && !"Destination".equals(t.head()) && !"ShipSpecificLiteral".equals(t.head()))
287 throw new RuntimeException(t+"");
288 String shipName = name(t.child(0));
289 String portName = name(t.child(1));
290 Ship ship = shipMap.get(shipName);
291 if (ship==null) throw new RuntimeException("no such ship \""+shipName+"\"");
294 if (b.getName().equals(portName))
296 throw new RuntimeException("no such pump \""+portName+"\"");
299 private HashMap<String,Integer> numAllocated = new HashMap<String,Integer>();
301 Ship allocateShip(String shipType) {
303 if (numAllocated.get(shipType) != null)
304 allocated = numAllocated.get(shipType);
305 numAllocated.put(shipType, allocated+1);
306 for(Iterator<Ship> it = fleet.iterator();
310 if (s.getType().equals(shipType)) {
311 if (allocated == 0) return s;
315 throw new RuntimeException("no more ships of type \""+shipType+"\"");
318 private long parseSSL(Tree t) {
319 String shipType = name(t.child(0));
320 String portName = name(t.child(1));
321 Ship chosenship = null;
322 for(Ship ship : fleet) {
323 if (ship.getType().equals(shipType)) {
328 if (chosenship==null) throw new RuntimeException("no ships of type " + shipType);
329 Dock chosenport = chosenship.getDock(portName);
330 Tree specs = t.child(2);
332 for(int i=0; i<specs.size(); i++) {
333 Tree tt = specs.child(i);
334 literal |= resolveLiteral(chosenport, stringBody(tt));
339 private static long resolveLiteral(Dock dd, String s) {
342 boolean hasval = false;
343 if (s.indexOf('=') != -1) {
344 val = Long.parseLong(s.substring(s.indexOf('=')+1));
345 s = s.substring(0, s.indexOf('='));
348 ShipDescription.Constant c = ((FleetTwoDock)dd).getConstant(s);
349 if (c==null) throw new RuntimeException("no constant " + s + " on dock " + dd);
353 ret |= ((~(0xffffffffffffffffL << c.numberWidth)) & val) << c.numberOffset;
357 private static FlagFunction parseFlags(Tree<String> t) {
358 FlagFunction ret = FlagFunction.ZERO;
359 for(int i=0; i<t.size(); i++) {
360 String s = t.child(i).head();
361 if (s.equals("0")) ret = ret.add(FlagFunction.ZERO);
362 if (s.equals("1")) ret = ret.add(FlagFunction.ONE);
363 if (s.equals("a")) ret = ret.add(FlagA);
364 if (s.equals("!a")) ret = ret.add(NotFlagA);
365 if (s.equals("b")) ret = ret.add(FlagB);
366 if (s.equals("!b")) ret = ret.add(NotFlagB);
367 if (s.equals("c")) ret = ret.add(FlagC);
368 if (s.equals("!c")) ret = ret.add(NotFlagC);
373 private int anoncount = 1;
374 void fillCodeBag(Tree<String> t, CodeBag cb) {
375 if (t.head()==null) return;
376 else if (t.head().equals("CodeBagDef")) {
377 CodeBag cb2 = getCodeBag(name(t.child(0)));
378 for(Tree<String> statement : t.child(1))
379 fillCodeBag(statement, cb2);
381 } else if (t.head().equals("Fiber")) {
382 Dock dock = (Dock)dock(t.child(0));
384 OUTER: for(Tree tt : t.child(1)) {
386 Predicate predicate = Default;
387 boolean looping = false;
388 boolean interruptible = false;
389 for(int i=0; i<tt.child(0).size(); i++) {
390 Tree ttt = tt.child(0).child(i);
391 if ("[a]".equals(ttt.head())) predicate = FlagA;
392 if ("[b]".equals(ttt.head())) predicate = FlagB;
393 if ("[c]".equals(ttt.head())) predicate = FlagC;
394 if ("[!a]".equals(ttt.head())) predicate = NotFlagA;
395 if ("[!b]".equals(ttt.head())) predicate = NotFlagB;
396 if ("[!c]".equals(ttt.head())) predicate = NotFlagC;
397 if ("[+]".equals(ttt.head())) predicate = IgnoreOLC;
398 if ("[I]".equals(ttt.head())) interruptible = true;
399 if ("[L]".equals(ttt.head())) looping = true;
402 if ("tail".equals(tt.head())) {
403 cb.add(new Tail(dock));
405 } else if ("setflags".equals(tt.head())) {
406 cb.add(new Set(dock, looping, predicate, parseFlags(tt.child(0)), parseFlags(tt.child(1))));
408 } else if ("tapl".equals(tt.head())) {
409 cb.add(new Set(dock, looping, predicate, SetDest.TAPL, path(dock, tt.child(0))));
411 } else if ("load".equals(tt.head()) && "loop".equals(tt.child(0).head())) {
412 cb.add(new Set(dock, looping, predicate, SetDest.OuterLoopCounter, SetSource.DataLatch));
414 } else if ("load".equals(tt.head()) && "repeat".equals(tt.child(0).head())) {
415 cb.add(new Set(dock, looping, predicate, SetDest.InnerLoopCounter, SetSource.DataLatch));
417 } else if ("*".equals(tt.head())) {
418 cb.add(new Set(dock, looping, predicate, SetDest.InnerLoopCounter, SetSource.Infinity));
420 } else if ("with".equals(tt.head()) && "loop".equals(tt.child(0).head())) {
421 cb.add(new Set(dock, looping, predicate, SetDest.OuterLoopCounter, (number(tt.child(1)))));
423 } else if ("with".equals(tt.head()) && "repeat".equals(tt.child(0).head())) {
424 cb.add(new Set(dock, looping, predicate, SetDest.InnerLoopCounter, (number(tt.child(1)))));
426 } else if ("decrement".equals(tt.head())) {
427 cb.add(new Set(dock, looping, predicate, SetDest.OuterLoopCounter, SetSource.Decrement));
429 } else if ("literal".equals(tt.head())) {
431 if (tt.child(0).head().equals("CodeBagBody")) {
432 Tree<String> tq = tt;
433 CodeBag cb2 = getCodeBag("anon"+(anoncount++));
434 for(Tree<String> statement : tq.child(0))
435 fillCodeBag(statement, cb2);
436 cb.add(new Set(dock, looping, predicate, SetDest.DataLatch, (cb2.getFakeAddress())), true);
438 } else if (tt.child(0).head().equals("Name")) {
439 String refname = name(tt.child(0));
440 CodeBag cb2 = getCodeBag(refname);
441 cb.add(new Set(dock, looping, predicate, SetDest.DataLatch, (cb2.getFakeAddress())), true);
443 } else if (tt.child(0).head().equals("[")) {
444 literal = parseSSL(tt.child(0));
446 literal = number(tt.child(0));
449 if ("int".equals(tt.child(1).head())) {
450 count = (int)number(tt.child(1));
451 } else if ("forever".equals(tt.child(1).head())) {
456 if (FleetTwoFleet.isSmallEnoughToFit(literal)) {
457 cb.add(new Set(dock, looping, predicate, SetDest.DataLatch, (literal)));
459 // FIXME bitwidth hardwired!
460 cb.add(new Shift(dock, looping, predicate, new BitVector(37).set(getField(36, 19, literal))));
461 cb.add(new Shift(dock, looping, predicate, new BitVector(37).set(getField(18, 0, literal))));
467 boolean requeue = false;
468 ttx = tt.child(1).head().equals("Commands") ? tt.child(1) : tt;
469 if ("int".equals(tt.child(2).head())) {
470 count = (int)number(tt.child(2));
472 } else if ("forever".equals(tt.child(2).head())) {
477 if (tt.head().equals("[*]")) {
478 cb.add(new Set(dock, looping, predicate, SetDest.InnerLoopCounter, SetSource.Infinity));
481 } else if (tt.head().equals("int")) {
482 count = (int)number(tt);
485 boolean tokenIn = false;
486 boolean dataIn = false;
487 boolean latch = false;
488 boolean dataOut = false;
489 boolean tokenOut = false;
490 boolean dispatch = false;
491 boolean localLiteral = false;
492 boolean ignoreUntilLast = false;
495 for(int i=0; i<ttx.size(); i++) {
496 Tree ttt = ttx.child(i);
497 if ("wait".equals(ttt.head())) { tokenIn = true; }
498 else if ("nop".equals(ttt.head())) { }
499 else if ("discard".equals(ttt.head())) { dataIn = true; latch = false; }
500 else if ("take".equals(ttt.head())) { dataIn = true; latch = true; }
501 else if ("recv".equals(ttt.head())) { dataIn = true; latch = true; }
502 else if ("collect".equals(ttt.head())) { dataIn = true; latch = true; }
503 else if ("recieve".equals(ttt.head())) { dataIn = true; latch = true; }
504 else if ("send".equals(ttt.head())) { dispatch = true; dataOut = true; }
505 else if ("sendto".equals(ttt.head())) { dataOut = true; path = path(dock, ttt.child(0)); }
506 else if ("deliver".equals(ttt.head())) { dataOut = true; }
507 else if ("notify".equals(ttt.head())) { tokenOut = true; path = path(dock, ttt.child(0)); }
508 else if ("notifyLast".equals(ttt.head())) { tokenOut = true; ignoreUntilLast = true; path = path(dock, ttt.child(0)); }
510 cb.add(new Move(dock, looping, predicate,
511 interruptible, path, tokenIn, dataIn,
512 latch, dispatch, dataOut, tokenOut));
517 private class CodeBag extends ArrayList<Instruction> {
518 public long address = -1;
519 public final String name;
520 private HashSet<Integer> isCBD = new HashSet<Integer>();
521 public CodeBag() { codeBags.add(this); this.name = "root"; }
522 public CodeBag(String name) { codeBags.add(this); codeBagsByName.put(name, this); this.name = name; }
523 public long getFakeAddress() { return codeBags.indexOf(this); }
524 public boolean equals(Object o) { return this==o; }
525 public void add(Instruction i, boolean isCBD) {
526 if (isCBD) this.isCBD.add(size());
532 public static ArrayList<Long> expect;
533 public static boolean skip;
535 private static long number(Tree t) {
537 for(Object c : t.child(2)) ret += ((Tree)c).head();
538 boolean negative = "-".equals(t.child(0).head());
541 if ("0x".equals(t.child(1).head())) val = Long.parseLong(ret, 16);
542 else if ("0b".equals(t.child(1).head())) val = Long.parseLong(ret, 2);
543 else val = Long.parseLong(ret);
544 if (negative) val = -1L * val;
548 * This interface marks Fleets which can create ships on the fly, like the fleeterpreter;
549 * if available, the parser will use this interface to create ships out of #ship definitions.
551 public static interface FleetWithDynamicShips {
552 public Ship createShip(String shiptype, String shipname);
555 private static Move discard(Dock dock) { return new Move(dock, false, IgnoreOLC, false, null, false, true, false, false, false, false); }
556 private static Move deliver(Dock dock) { return new Move(dock, false, IgnoreOLC, false, null, false, false, false, false, true, false); }
557 private static Move wait(Dock dock) { return new Move(dock, false, IgnoreOLC, false, null, true, false, false, false, false, false); }
558 private static Move sendto(Dock dock, Path path) { return new Move(dock, false, IgnoreOLC, false, path, false, false, false, false, true, false); }