8f48fef1e2e5d66dc7e816b16f03388be2ce2d42
[fleet.git] / src / edu / berkeley / fleet / ir / Process.java
1 package edu.berkeley.fleet.ir;
2 import edu.berkeley.fleet.loops.*;
3 import java.util.concurrent.Semaphore;
4 import java.util.*;
5 import java.net.*;
6 import edu.berkeley.fleet.two.*;
7 import edu.berkeley.fleet.api.*;
8 import edu.berkeley.fleet.fpga.*;
9 import edu.berkeley.fleet.api.Instruction.*;
10 import edu.berkeley.fleet.api.Instruction.Set;
11 import edu.berkeley.fleet.api.Instruction.Set.*;
12 import static edu.berkeley.fleet.api.Predicate.*;
13 import static edu.berkeley.fleet.util.BitManipulations.*;
14
15
16 /*
17   - refactor the cleanup into the subclasses of Port (phase1, phase2, etc)
18 */
19
20 // does peer.recvWord() have to honor the currently-set predicate?
21
22 // public class ReplaceModule extends Module { }
23 // public class CountMergeModule extends Module { }
24 // public class SortMergeModule extends Module { }
25 // public class FanOutModule extends Module { }
26 // public class MemoryModule extends Module { }
27 // public class DoneModule extends Module { }
28
29 public class Process {
30
31
32     public static int reset_count = 0;
33     public static HashSet<Dock> torpedoes = new HashSet<Dock>();
34
35     public final Fleet    fleet;
36     public final ShipPool pool;
37
38     public Process(Fleet fleet) {
39         this.fleet = fleet;
40         this.pool  = new ShipPool(fleet);
41     }
42
43     private HashSet<Module> modules = new HashSet<Module>();
44
45     public void build(Context ctx) {
46         for(Module mod : modules)
47             mod.build(ctx);
48     }
49     public void reset(Context ctx, int phase, Destination ackDestination) {
50         reset_count = 0;
51         torpedoes.clear();
52         for(Module mod : modules)
53             mod.reset(ctx, phase, ackDestination);
54     }
55
56     public class Module {
57
58         void doReset(Context ctx, int phase, Dock dock, Port peer, Destination ackDestination, boolean peerUsed) {
59             if (dock.getShip().getType().equals("Debug")) return;
60
61             switch(phase) {
62
63                 // Phase 0: torpedo every output dock, put it in
64                 // collecting mode.  Cannot combine with phase 1,
65                 // because until output docks are in vacuum mode we
66                 // cannot be sure that the tokens to the input docks
67                 // will eventually succeed.  This may cause the
68                 // instructions sent after the tokens to back up into
69                 // the switch fabric.
70                 case 0: {
71                     if (!dock.isInputDock()) {
72                         torpedoes.add(dock);
73                         LoopFactory lf = new LoopFactory(ctx, dock, 1);
74                         lf.sendToken(ackDestination);
75                         lf = lf.makeNext(0);
76                         lf.abortLoopIfTorpedoPresent();
77                         lf.collectWord();
78                         reset_count++;
79                     }
80                     break;
81                 }
82
83                 // Phase 1: torpedo every input dock, put it in loopback mode
84                 case 1: {
85                     if (dock.isInputDock()) {
86                         torpedoes.add(dock);
87                         LoopFactory lf = new LoopFactory(ctx, dock, 1);
88                         lf.sendToken(ackDestination);
89
90                         // FIXME: this won't work right for ports that
91                         // get "shared" by two senders (for example,
92                         // inAddrRead1/2)
93
94                         if (peerUsed && peer!=null) {
95                             lf = lf.makeNext(0);
96                             lf.abortLoopIfTorpedoPresent();
97                             ((OutPort)peer).recvWord(lf);
98                             ((OutPort)peer).sendToken(lf);
99                         }
100                         reset_count++;
101                     }
102                     break;
103                 }
104
105                 // Phase 2: torpedo every output dock, have it absorb tokens
106                 case 2: {
107                     if (!dock.isInputDock()) {
108                         torpedoes.add(dock);
109                         LoopFactory lf = new LoopFactory(ctx, dock, 1);
110                         if (peer != null)
111                             for(int i=0; i<((InPort)peer).getTokensToAbsorb(); i++)
112                                 lf.recvToken();
113                         lf.sendToken(ackDestination);
114                         reset_count++;
115                     }
116                     break;
117                 }
118
119                 // Phase 3: torpedo every input dock, and we're done
120                 case 3: {
121                     if (dock.isInputDock()) {
122                         if (peerUsed && peer!=null) {
123                             torpedoes.add(dock);
124                         }
125                         LoopFactory lf = new LoopFactory(ctx, dock, 1);
126                         lf.sendToken(ackDestination);
127                         reset_count++;
128                     }
129                     break;
130                 }
131
132
133             }
134         }
135
136         public Module() {
137             Process.this.modules.add(this);
138         }
139
140         private HashMap<String,Port> ports = new HashMap<String,Port>();
141
142         public InPort  getInPort(String name)  { return (InPort)ports.get(name); }
143         public OutPort getOutPort(String name) { return (OutPort)ports.get(name); }
144         
145         public void build(Context ctx) { for(Port p : ports.values()) p.build(ctx); }
146         public void reset(Context ctx, int phase, Destination ackDestination) {
147             for(Port p : ports.values()) p.reset(ctx, phase, ackDestination);
148         }
149
150         public abstract class Port {
151             public final String name;
152             public Port(String name) {
153                 this.name = name;
154                 if (Module.this.ports.get(name)!=null) throw new RuntimeException();
155                 Module.this.ports.put(name,this);
156             }
157             public abstract void build(Context ctx);
158             public abstract void reset(Context ctx, int phase, Destination ackDestination);
159         }
160
161         public abstract class InPort extends Port {
162             OutPort peer;
163             public InPort(String name) { super(name); }
164             public void connect(OutPort peer) {
165                 this.setPeer(peer);
166                 peer.setPeer(this);
167             }
168             public void setPeer(OutPort peer) {
169                 if (this.peer!=null) throw new RuntimeException("cannot call setPeer() twice");
170                 this.peer = peer;
171             }
172
173             /** this port's peer (an OutPort) invokes this to have "recvToken" or equivalent inserted */
174             public abstract void recvToken(LoopFactory loopfactory_at_output_dock);
175             /** this port's peer (an OutPort) invokes this to have "sendWord" or equivalent inserted */
176             public abstract void sendWord(LoopFactory loopfactory_at_output_dock);
177
178             public int getTokensToAbsorb() { return 0; }
179         }
180
181         public abstract class OutPort extends Port {
182             InPort peer;
183             public OutPort(String name) { super(name); }
184             public void connect(InPort peer) {
185                 this.setPeer(peer);
186                 peer.setPeer(this);
187             }
188             public void setPeer(InPort peer) {
189                 if (this.peer!=null) throw new RuntimeException("cannot call setPeer() twice");
190                 this.peer = peer;
191             }
192
193             /** this port's peer (an InPort) invokes this to have "sendToken" or equivalent inserted */
194             public abstract void sendToken(LoopFactory loopfactory_at_input_dock);
195             /** this port's peer (an InPort) invokes this to have "recvWord" or equivalent inserted */
196             public abstract void recvWord(LoopFactory loopfactory_at_input_dock);
197         }
198
199         public final class DockInPort extends InPort {
200             final Dock dock;
201             int count;
202             BitVector[] pattern;
203             public DockInPort(String name, Dock dock) { this(name, dock, 0); }
204             public DockInPort(String name, Dock dock, int count) { this(name, dock, count, new BitVector[] { null }); }
205             public DockInPort(String name, Dock dock, int count, BitVector[] pattern) {
206                 super(name);
207                 this.dock = dock;
208                 this.count = count;
209                 this.pattern = pattern;
210             }
211             public void recvToken(LoopFactory lf) { lf.recvToken(); }
212             public void sendWord(LoopFactory lf) { lf.sendWord(dock.getDataDestination()); }
213             public void build(Context ctx) { build(ctx, new LoopFactory(ctx, dock, 1)); }
214             // number-in-flight is considered a property of the input dock in a pair
215             //public int getInflight() { return 4; }
216             public int getInflight() { return 1; }
217             public int getTokensToAbsorb() { return getInflight(); }
218             private boolean peerUsed() {
219                 if (peer==null) return false;
220                 for(int i=0; i<pattern.length; i++) if (pattern[i]==null) return true;
221                 return false;
222             }
223             public void reset(Context ctx, int phase, Destination ackDestination) {
224                 doReset(ctx, phase, dock, peer, ackDestination, peerUsed());
225             }
226             protected void build(Context ctx, LoopFactory lf) {
227                 int inflight = (count != 0 && count < getInflight()) ? count : getInflight();
228
229                 if (peer!=null)
230                     for(int i=0; i<inflight; i++) peer.sendToken(lf);
231
232                 lf = lf.makeNext(count);
233                 for(int i=0; i<pattern.length; i++) {
234                     if (pattern[i]==null) {
235                         if (peer!=null) {
236                             lf.abortLoopIfTorpedoPresent();
237                             peer.recvWord(lf);
238                             peer.sendToken(lf);
239                             lf.deliver();
240                         } else {
241                             lf.interruptibleNop();
242                         }
243                     } else {
244                         lf.literal(pattern[i]);
245                         lf.abortLoopIfTorpedoPresent();
246                         lf.deliver();
247                     }
248                 }
249
250                 if (count!=0) {
251                     // "torpedoable nop" to keep the dock in a receptive state
252                     lf.abortLoopIfTorpedoPresent();
253                     lf.recvToken();
254                 }
255             }
256         }
257
258         public /*final*/ class DockOutPort extends OutPort {
259             public final Dock dock;
260             public final int count;
261             public DockOutPort(String name, Dock dock) { this(name, dock, 0); }
262             public DockOutPort(String name, Dock dock, int count) { super(name); this.dock = dock; this.count = count; }
263             public void sendToken(LoopFactory lf) { lf.sendToken(dock.getDataDestination()); }
264             public void recvWord(LoopFactory lf) { lf.recvWord(); }
265             public void build(Context ctx) { build(ctx, new LoopFactory(ctx, dock, 1)); }
266             protected void build(Context ctx, LoopFactory lf) {
267                 if (peer==null) return;
268                 lf = lf.makeNext(count);
269                 lf.abortLoopIfTorpedoPresent();
270                 peer.recvToken(lf);
271                 lf.collectWord();
272                 peer.sendWord(lf);
273             }
274             public void reset(Context ctx, int phase, Destination ackDestination) {
275                 doReset(ctx, phase, dock, peer, ackDestination, true);
276             }
277         }
278     }
279
280     private static BitVector bv(long l) { return new BitVector(/*FIXME fleet.getWordWidth()*/37).set(l); }
281     private static BitVector[] bv(long[] l) {
282         BitVector[] ret = new BitVector[l.length];
283         for(int i=0; i<ret.length; i++) ret[i] = bv(l[i]);
284         return ret;
285     }
286
287     /**
288      *  Deliver the constant at out forever.  Flow control in<->out is
289      *  maintained, but out is not flow-controlled, so be sure
290      *  that every datum sent there is consumed synchronously wiht
291      *  data items sent to out.
292      */
293     public class ForeverModule extends Module {
294         private BitVector bv;
295         public final OutPort out = new OutPort("out") {
296                 public void sendToken(LoopFactory lf) { }
297                 public void recvWord(LoopFactory lf) { }
298                 public void build(Context ctx) { }
299                 public void reset(Context ctx, int phase, Destination ackDestination) { }
300                 public void setPeer(InPort peer) {
301                     this.peer = peer;
302                     DockInPort pip = ((DockInPort)peer);
303                     for(int i=0; i<pip.pattern.length; i++) {
304                         if (pip.pattern[i]==null)
305                             pip.pattern[i] = bv;
306                     }
307                 }
308             };
309         public ForeverModule(long l) { this(new BitVector(fleet.getWordWidth()).set(l)); }
310         public ForeverModule(final BitVector bv) { this.bv = bv; }
311     }
312
313     public class OnceModule extends Module {
314         private BitVector bv;
315         public final OutPort out = new OutPort("out") {
316                 public void sendToken(LoopFactory lf) { }
317                 public void recvWord(LoopFactory lf) { }
318                 public void build(Context ctx) { }
319                 public void reset(Context ctx, int phase, Destination ackDestination) { }
320                 public void setPeer(InPort peer) {
321                     this.peer = peer;
322                     DockInPort pip = ((DockInPort)peer);
323                     BitVector[] pip_pattern = pip.pattern;
324                     BitVector[] temp = new BitVector[pip_pattern.length * 2];
325                     int j = 0;
326                     int i = 0;
327                     boolean done = false;
328                     // FIXME: if peer.count is already 1, this gets simpler and different
329                     for(i=0; i<temp.length; i++) {
330                         if (pip_pattern[j] != null) {
331                             temp[i] = pip_pattern[j];
332                         } else {
333                             if (done) break;
334                             done = true;
335                             temp[i] = bv;
336                         }
337                         j++;
338                         if (j >= pip_pattern.length) j = 0;
339                     }
340                     pip.pattern = new BitVector[i];
341                     System.arraycopy(temp, 0, pip.pattern, 0, i);
342                     pip.count = 1;
343                 }
344             };
345         public OnceModule(long l) { this(new BitVector(fleet.getWordWidth()).set(l)); }
346         public OnceModule(final BitVector bv) { this.bv = bv; }
347     }
348
349     public class DebugModule extends Module {
350         public final Ship ship = pool.allocateShip("Debug");
351         public final InPort in = new DockInPort("in", ship.getDock("in"));
352         // NOTE: shutdown needs to treat this specially
353         public DebugModule() { }
354     }
355
356     public class UnPunctuatorModule extends Module {
357         private final Ship    ship  = pool.allocateShip("Counter");
358         public  final OutPort out   = new DockOutPort("out", ship.getDock("out"));
359         public  final InPort  val   = new DockInPort("in1",  ship.getDock("in1"));
360         public  final InPort  count = new DockInPort("in2",  ship.getDock("in2"), 0, new BitVector[] { null, bv(1) });
361         public  final InPort  op    = new DockInPort("inOp", ship.getDock("inOp"), 0, new BitVector[] { bv(6 /*PASS_C2_V1*/), bv(10 /*DROP_C2_V1*/) } );
362         public UnPunctuatorModule() { }
363     }
364
365     public class PunctuatorModule extends Module {
366         private final long    punc;
367         private final Ship    ship  = pool.allocateShip("Counter");
368         public  final OutPort out   = new DockOutPort("out", ship.getDock("out"));
369         public  final InPort  val   = new DockInPort("in1",  ship.getDock("in1"));
370         public  final InPort  op    = new DockInPort("inOp", ship.getDock("inOp"), 0, new BitVector[] { bv(6 /*PASS_C2_V1*/), bv(7 /*PASS_C2_V2*/) } );
371         public  final InPort  count;
372         public PunctuatorModule(long punc) {
373             this.punc = punc;
374             this.count = new DockInPort("in2",  ship.getDock("in2"), 0, new BitVector[] { null, bv(1), bv(punc) });
375         }
376     }
377
378     public class AluModule extends Module {
379         public final Ship    ship = pool.allocateShip("Alu");
380         public final InPort  in1 = new DockInPort("in1",  ship.getDock("in1"));
381         public final InPort  in2 = new DockInPort("in2",  ship.getDock("in2"));
382         public final InPort  inOp = new DockInPort("inOp", ship.getDock("inOp"));
383         public final OutPort out  = new DockOutPort("out", ship.getDock("out"));
384         public AluModule() { }
385     }
386
387     public class DownCounterModule extends Module {
388         public final Ship    ship  = pool.allocateShip("Counter");
389         public final InPort  start = new DockInPort("in1",  ship.getDock("in1"));
390         public final InPort  incr  = new DockInPort("in2",  ship.getDock("in2"));
391         public final InPort  inOp  = new DockInPort("inOp", ship.getDock("inOp"), 0, new BitVector[] { bv(12 /*COUNTDOWN*/) });
392         public final OutPort out   = new DockOutPort("out", ship.getDock("out"));
393         public DownCounterModule() { }
394     }
395
396     public class RepeatModule extends Module {
397         public final Ship    ship   = pool.allocateShip("Counter");
398         public final InPort  count  = new DockInPort("in1",  ship.getDock("in1"));
399         public final InPort  val    = new DockInPort("in2",  ship.getDock("in2"));
400         public final InPort  inOP   = new DockInPort("inOp", ship.getDock("inOp"), 0, new BitVector[] { bv(1 /*REPEAT_C1_V2*/) });
401         public final OutPort out    = new DockOutPort("out", ship.getDock("out"));
402         public RepeatModule() { }
403     }
404
405     public class SortedMergeModule extends Module {
406         public final Ship    ship = pool.allocateShip("Alu");
407         public final InPort  in1  = new DockInPort("in1",  ship.getDock("in1"));
408         public final InPort  in2  = new DockInPort("in2",  ship.getDock("in2"));
409         public final InPort  inOp = new DockInPort("inOp", ship.getDock("inOp"), 0, new BitVector[] { bv(9 /*MAXMERGE*/) });
410         public final OutPort out  = new DockOutPort("out", ship.getDock("out"));
411         public SortedMergeModule() { }
412     }
413
414     public class MemoryModule extends Module {
415         public final Ship    ship;
416         public final InPort  inCBD;
417         public final InPort  inAddrRead1;
418         public final InPort  inAddrRead2;
419         public final InPort  inAddrWrite;
420         public final InPort  inDataWrite;
421         public final OutPort outRead1;
422         public final OutPort outRead2;
423         public final OutPort outWrite;
424         public MemoryModule(Ship memoryShip) {
425             this.ship = memoryShip;
426             this.inCBD        = ship.getType().equals("Memory") ? new DockInPort("inCBD", ship.getDock("inCBD")) : null;
427             this.inAddrWrite  = new DockInPort("inAddrWrite", ship.getDock("inAddrWrite"));
428             this.inDataWrite  = new DockInPort("inDataWrite", ship.getDock("inDataWrite"));
429             this.inAddrRead1  = new InPort("inAddrRead1") {
430                     public void recvToken(LoopFactory lf) { lf.recvToken(); }
431                     public void sendWord(LoopFactory lf) { lf.sendWord(ship.getDock("inAddrRead").getDataDestination(), new BitVector(1).set(0)); }
432                     public void build(Context ctx) { }
433                     public int getTokensToAbsorb() { return outRead1.peer.getTokensToAbsorb(); }
434                     public void reset(Context ctx, int phase, Destination ackDestination) {
435                         doReset(ctx, phase, ship.getDock("inAddrRead"), null, ackDestination, false);
436                     }
437                 };
438             this.inAddrRead2  = new InPort("inAddrRead2") {
439                     public void recvToken(LoopFactory lf) { lf.recvToken(); }
440                     public void sendWord(LoopFactory lf) { lf.sendWord(ship.getDock("inAddrRead").getDataDestination(), new BitVector(1).set(1)); }
441                     public void build(Context ctx) { }
442                     public int getTokensToAbsorb() { return outRead2.peer.getTokensToAbsorb(); }
443                     public void reset(Context ctx, int phase, Destination ackDestination) { }
444                 };
445             this.outRead1 = new OutPort("outRead1") {
446                     public void sendToken(LoopFactory lf) { inAddrRead1.peer.sendToken(lf); }
447                     public void recvWord(LoopFactory lf) { lf.recvWord(); }
448                     public void build(Context ctx) { }
449                     public void reset(Context ctx, int phase, Destination ackDestination) { }
450                 };
451             this.outRead2 = new OutPort("outRead2") {
452                     public void sendToken(LoopFactory lf) { inAddrRead2.peer.sendToken(lf); }
453                     public void recvWord(LoopFactory lf) { lf.recvWord(); }
454                     public void build(Context ctx) { }
455                     public void reset(Context ctx, int phase, Destination ackDestination) { }
456                 };
457             this.outWrite = new DockOutPort("out", ship.getDock("out")) {
458                     protected void build(Context ctx, LoopFactory lf) {
459                         lf = lf.makeNext(0);
460                         lf.abortLoopIfTorpedoPresent();
461                         lf.collectWord();
462                         
463                         lf.setFlags(FlagFunction.ZERO, FlagFunction.ZERO.add(FlagC));
464                         if (this.peer != null) {
465                             lf.setPredicate(Predicate.FlagB);
466                             lf.literal(77);
467                             lf.abortLoopIfTorpedoPresent();
468                             this.peer.recvToken(lf);
469                             this.peer.sendWord(lf);
470                         }
471                         
472                         lf.setPredicate(Predicate.NotFlagB);
473                         lf.abortLoopIfTorpedoPresent();
474                         lf.recvToken();
475                         lf.setFlags(FlagFunction.ZERO.add(NotFlagC).add(FlagB), FlagFunction.ZERO.add(FlagC).add(FlagB));
476                         if (outRead1.peer != null) {
477                             lf.setPredicate(Predicate.NotFlagB);
478                             outRead1.peer.sendWord(lf);
479                         }
480                         if (outRead2.peer != null) {
481                             lf.setPredicate(Predicate.NotFlagA);
482                             outRead2.peer.sendWord(lf);
483                         }
484                         lf.setPredicate(null);
485                     }
486                 };
487         }
488         public void build(Context ctx) {
489             super.build(ctx);
490             LoopFactory lf;
491
492             lf = new LoopFactory(ctx, ship.getDock("inAddrRead"), 0);
493             lf.abortLoopIfTorpedoPresent();
494             lf.recvWord();
495             lf.setFlags(FlagFunction.ZERO.add(FlagC), FlagFunction.ZERO);
496             lf.setPredicate(Predicate.NotFlagA);
497             lf.sendToken(ship.getDock("out").getDataDestination(), new BitVector(1).set(0));
498             lf.setPredicate(Predicate.FlagA);
499             lf.sendToken(ship.getDock("out").getDataDestination(), new BitVector(1).set(1));
500             lf.setPredicate(null);
501             lf.deliver();
502         }
503     }
504
505     public static void main(String[] s) throws Exception {
506         Fleet fleet = new Fpga();
507         //Fleet fleet = new Interpreter(false);
508
509         Random random = new Random(System.currentTimeMillis());
510         long[] vals = new long[256];
511         for(int i=0; i<vals.length; i++) {
512             vals[i] = Math.abs(random.nextInt());
513         }
514
515         Ship mem1 = fleet.getShip("Memory", 0);
516         Ship mem2 = fleet.getShip("Memory", 1);
517         //Ship mem2 = fleet.getShip("DDR2", 0);
518
519         FleetProcess fp;
520         int stride = 1;
521         fp = null;
522
523         fp = fleet.run(new Instruction[0]);
524         Gadgets.writeMem(fp, mem1, 0, bv(vals));
525         int vals_length = vals.length;
526
527         // Disable readback/writeback inside the loop
528         vals = null;
529
530         while(stride < vals_length) {
531             
532             // reset the FleetProcess
533             //fp.terminate(); fp = null;
534
535             System.out.println("stride " + stride);
536
537             // if we reset the FleetProcess, restart it
538             if (fp==null) fp = fleet.run(new Instruction[0]);
539
540             // do the mergeSort
541             vals = mergeSort(fp, fleet, vals, vals_length, stride, mem1, mem2);
542
543             // verify the cleanup
544             //verifyClean(fp);
545
546             Ship mem = mem1; mem1=mem2; mem2=mem;
547
548             stride = stride * 2;
549             System.out.println();
550         }
551
552         BitVector[] bvs = new BitVector[vals_length];
553         Gadgets.readMem(fp, mem1, 0, bvs);
554         System.out.println("results:");
555         for(int i=0; i<vals_length; i++)
556             System.out.println(bvs[i].toLong());
557     }
558
559     // FIXME: check for "lingering" torpedoes?
560     public static void verifyClean(FleetProcess fp) {
561         Ship debug   = fp.getFleet().getShip("Debug", 0);
562         Dock debugIn = debug.getDock("in");
563
564         Context ctx;
565         LoopFactory lf;
566
567         ctx = new Context(fp.getFleet());
568         lf = new LoopFactory(ctx, debugIn, 1);
569         lf.literal(12);
570         lf.deliver();
571         lf.literal(5);
572         lf.deliver();
573         Gadgets.dispatch(fp, ctx);
574         fp.flush();
575
576         System.out.println("checking debug.in");
577         if (fp.recvWord().toLong() != 12) throw new RuntimeException("debug dock not properly initialized");
578         if (fp.recvWord().toLong() != 5)  throw new RuntimeException("debug dock not properly initialized");
579
580         long k = 0;
581         for(Ship ship : fp.getFleet())
582             if (!"Debug".equals(ship.getType()))
583                 for (Dock dock : ship) {
584                     System.out.print("checking " + dock + "                     ");
585
586                     k = (k + 23) % 65535;
587                     ctx = new Context(fp.getFleet());
588
589                     boolean reverse = (k%2)==0;
590
591                     lf = new LoopFactory(ctx, debugIn, 4);
592                     lf.recvToken();
593                     lf.setFlags(FlagFunction.ZERO.add(FlagC), FlagFunction.ZERO);
594                     lf.setPredicate(Predicate.NotFlagA);
595                     lf.literal(k);
596                     lf.setPredicate(Predicate.FlagA);
597                     lf.literal(k+1);
598                     lf.setPredicate(null);
599                     lf.deliver();
600
601                     lf = new LoopFactory(ctx, dock, 1);
602                     lf.sendToken(debugIn.getDataDestination(), new BitVector(1).set(reverse ? 1 : 0));
603                     lf.sendToken(debugIn.getDataDestination(), new BitVector(1).set(reverse ? 0 : 1));
604                     lf.sendToken(dock.getDataDestination(), new BitVector(1).set(reverse ? 1 : 0));
605                     lf.sendToken(dock.getDataDestination(), new BitVector(1).set(reverse ? 0 : 1));
606                     lf = lf.makeNext(2);
607
608                     // if a torpedo was lying in wait, the problem will be manifest as a "freezup"
609                     lf.abortLoopIfTorpedoPresent();
610
611                     lf.recvToken();
612                     lf.setFlags(FlagFunction.ZERO.add(FlagC), FlagFunction.ZERO);
613                     lf.setPredicate(Predicate.NotFlagA);
614                     lf.sendToken(debugIn.getDataDestination(), new BitVector(1).set(0));
615                     lf.setPredicate(Predicate.FlagA);
616                     lf.sendToken(debugIn.getDataDestination(), new BitVector(1).set(1));
617                     lf.setPredicate(null);
618
619                     Gadgets.dispatch(fp, ctx);
620                     fp.flush();
621
622                     long kk;
623                     for(int i=0; i<4; i++) {
624                         kk = fp.recvWord().toLong();
625                         System.out.print("\rchecking " + dock + " (got "+(i+1)+")");
626                         if (kk != ((reverse ^ (i%2!=0)) ? k+1 : k)) {
627                             System.out.println();
628                             throw new RuntimeException(dock+" not properly initialized ("+(i+1)+")");
629                         }
630                     }
631                     System.out.println();
632                 }
633     }
634
635     public static long[] mergeSort(FleetProcess fp, Fleet fleet,
636                                    long[] vals, int vals_length, int stride_length,
637                                    Ship memoryShip1, Ship memoryShip2) throws Exception {
638
639         if (vals != null) {
640             BitVector[] mem = new BitVector[vals_length];
641             for(int i=0; i<mem.length; i++) mem[i] = new BitVector(fleet.getWordWidth()).set(vals[i]);
642             Gadgets.writeMem(fp, memoryShip1, 0, mem);
643         }
644
645         //////////////////////////////////////////////////////////////////////////////
646
647         Process proc = new Process(fleet);
648         DebugModule dm = proc.new DebugModule();
649
650         int end_of_data = vals_length;
651         int num_strides = end_of_data / (stride_length * 2);
652
653         MemoryModule mm  = proc.new MemoryModule(memoryShip1);
654         SortedMergeModule sm = proc.new SortedMergeModule();
655
656         // So far: we have four spare Counter ships; one can be used for resetting
657         for(int i=0; i<2; i++) {
658
659             DownCounterModule c0 = proc.new DownCounterModule();
660             DownCounterModule c1 = proc.new DownCounterModule();
661
662             c0.start.connect(proc.new ForeverModule(stride_length).out);
663             c0.incr.connect(proc.new ForeverModule(1).out);
664
665             c1.start.connect(proc.new OnceModule(end_of_data + i*stride_length).out);
666             c1.incr.connect(proc.new OnceModule(stride_length*2).out);
667
668             RepeatModule r1 = proc.new RepeatModule();
669             r1.val.connect(c1.out);
670             r1.count.connect(proc.new ForeverModule(stride_length).out);
671
672             AluModule alu = proc.new AluModule();
673             alu.in1.connect(r1.out);
674             alu.in2.connect(c0.out);
675             alu.inOp.connect(proc.new ForeverModule(2).out);  // ADD
676             alu.out.connect(i==0 ? mm.inAddrRead1 : mm.inAddrRead2);
677
678             PunctuatorModule punc = proc.new PunctuatorModule(-1);
679             punc.count.connect(proc.new ForeverModule(stride_length).out);
680             punc.val.connect(i==0 ? mm.outRead1 : mm.outRead2);
681             punc.out.connect(i==0 ? sm.in1 : sm.in2);
682         }
683
684         UnPunctuatorModule unpunc = proc.new UnPunctuatorModule();
685         unpunc.val.connect(sm.out);
686         unpunc.count.connect(proc.new ForeverModule(2*stride_length).out);
687
688         DownCounterModule cw = proc.new DownCounterModule();
689         cw.start.connect(proc.new OnceModule(end_of_data).out);
690         cw.incr.connect(proc.new OnceModule(1).out);
691
692         MemoryModule mm2 = proc.new MemoryModule(memoryShip2);
693         mm2.inAddrWrite.connect(cw.out);
694         mm2.inDataWrite.connect(unpunc.out);
695         mm2.outWrite.connect(dm.in);
696
697         //////////////////////////////////////////////////////////////////////////////
698
699         Context ctx = new Context(fp.getFleet());
700         ctx.setAutoflush(true);
701
702         ArrayList<Instruction> ai = new ArrayList<Instruction>();
703         proc.build(ctx);
704         ctx.emit(ai);
705         for(Instruction ins : ai) {
706             //System.out.println(ins);
707             fp.sendInstruction(ins);
708         }
709         fp.flush();
710
711         for(int i=0; i<vals_length; i++) {
712             System.out.print("\rreading back... " + i+"/"+vals_length+"  ");
713             BitVector rec = fp.recvWord();
714             System.out.print(" (prev result: " + rec + " = " + rec.toLong() + ")");
715         }
716         System.out.println("\rdone.                                                                    ");
717
718         //if (true) return ret;
719
720         Context ctx2 = new Context(fp.getFleet());
721         Dock debugIn = fleet.getShip("Debug",0).getDock("in");
722         Dock fred = debugIn;
723         fp.sendToken(debugIn.getInstructionDestination());
724         fp.flush();
725
726         LoopFactory lf = new LoopFactory(ctx2, debugIn, 0);
727         lf.literal(0);
728         lf.abortLoopIfTorpedoPresent();
729         lf.recvToken();
730         lf.deliver();
731
732         Gadgets.dispatch(fp, ctx2);
733         fp.flush();
734
735         int count = 0;
736
737         Ship counter = proc.pool.allocateShip("Counter");
738
739         for(int phase=0; phase<=3; phase++) {
740             System.out.println("== phase "+phase+" ==================================================================");
741             ctx2 = new Context(fp.getFleet());
742
743             Destination ackDestination = counter.getDock("in2").getDataDestination();
744             proc.reset(ctx2, phase, ackDestination);
745
746             Context ctx3 = new Context(fp.getFleet());
747             lf = new LoopFactory(ctx3, counter.getDock("inOp"), 1);
748             lf.literal(9);
749             lf.deliver();
750             lf.literal(5);
751             lf.deliver();
752             lf = new LoopFactory(ctx3, counter.getDock("in1"), 1);
753             lf.literal(reset_count-1);
754             lf.deliver();
755             lf.literal(1);
756             lf.deliver();
757             lf = new LoopFactory(ctx3, counter.getDock("in2"), 0);
758             lf.abortLoopIfTorpedoPresent();
759             lf.recvWord();
760             lf.deliver();
761             lf = new LoopFactory(ctx3, counter.getDock("out"), 1);
762             lf.collectWord();
763             lf.sendToken(counter.getDock("in2").getInstructionDestination());  // HACK: we don't check to make sure this hits
764             lf.sendToken(debugIn.getDataDestination());
765             Gadgets.dispatch(fp, ctx3);  // HACK: we don't check to make sure that this is "firmly in place"
766
767             for(Dock dock : torpedoes) fp.sendToken(dock.getInstructionDestination());
768             Gadgets.dispatch(fp, ctx2);
769             fp.flush();
770             System.out.println("flushed");
771
772             fp.recvWord();
773             System.out.println("phase done");
774
775             System.out.println();
776         }
777
778         fp.sendToken(debugIn.getInstructionDestination());
779         fp.flush();
780
781         //System.out.println("verifying cleanup:");
782         //verifyClean(fp);
783
784         System.out.println("reading back:");
785         long[] ret = null;
786         if (vals != null) {
787             ret = new long[vals_length];
788             BitVector[] mem = new BitVector[vals_length];
789             Gadgets.readMem(fp, memoryShip2, 0, mem);
790             for(int i=0; i<ret.length; i++) ret[i] = mem[i].toLong();
791         }
792         return ret;
793     }
794
795     private BitVector[] longsToBitVectors(long[] initialValues) {
796         BitVector[] bv = new BitVector[initialValues.length];
797         for(int i=0; i<initialValues.length; i++)
798             bv[i] = new BitVector(fleet.getWordWidth()).set(initialValues[i]);
799         return bv;
800     }
801 }
802
803