13f54a0188bbb4d62f763e8f6181c4b4569aceba
[Mograsim.git] / net.mograsim.logic.core / src / net / mograsim / logic / core / wires / CoreWire.java
1 package net.mograsim.logic.core.wires;
2
3 import static net.mograsim.logic.core.types.Bit.U;
4 import static net.mograsim.logic.core.types.Bit.Z;
5
6 import java.util.ArrayList;
7 import java.util.Arrays;
8 import java.util.HashSet;
9 import java.util.List;
10 import java.util.Set;
11
12 import net.mograsim.logic.core.LogicObservable;
13 import net.mograsim.logic.core.LogicObserver;
14 import net.mograsim.logic.core.timeline.Timeline;
15 import net.mograsim.logic.core.types.Bit;
16 import net.mograsim.logic.core.types.BitVector;
17 import net.mograsim.logic.core.types.BitVector.BitVectorMutator;
18
19 /**
20  * Represents an array of wires that can store n bits of information.
21  * 
22  * @author Fabian Stemmler
23  *
24  */
25 public class CoreWire
26 {
27         public final String name;
28         private BitVector cachedValues;
29         public final int travelTime;
30         private List<ReadEnd> attached = new ArrayList<>();
31         public final int width;
32         List<ReadWriteEnd> inputs = new ArrayList<>();
33         Timeline timeline;
34         private Bit[] bitsWithoutFusions;
35         FusedBit[] fusedBits;
36
37         public CoreWire(Timeline timeline, int width, int travelTime)
38         {
39                 this(timeline, width, travelTime, null);
40         }
41
42         public CoreWire(Timeline timeline, int width, int travelTime, String name)
43         {
44                 if (width < 1)
45                         throw new IllegalArgumentException(
46                                         String.format("Tried to create an array of wires with width %d, but a width of less than 1 makes no sense.", width));
47                 this.name = name;
48                 this.timeline = timeline;
49                 this.width = width;
50                 this.travelTime = travelTime;
51                 initValues();
52         }
53
54         private void initValues()
55         {
56                 cachedValues = U.toVector(width);
57                 bitsWithoutFusions = cachedValues.getBits();
58         }
59
60         private void setNewValues(BitVector newValues)
61         {
62                 cachedValues = newValues;
63                 notifyObservers();
64         }
65
66         private void invalidateCachedValuesForAllFusedWires()
67         {
68                 invalidateCachedValues();
69                 if (fusedBits != null)
70                         for (FusedBit fusion : fusedBits)
71                                 if (fusion != null)
72                                         fusion.invalidateCachedValuesForAllParticipatingWires();
73         }
74
75         private void invalidateCachedValues()
76         {
77                 cachedValues = null;
78                 notifyObservers();
79         }
80
81         void recalculateValuesWithoutFusions()
82         {
83                 Bit[] bits = new Bit[width];
84                 if (inputs.isEmpty())
85                         Arrays.fill(bits, U);
86                 else
87                 {
88                         System.arraycopy(inputs.get(0).getInputValues().getBits(), 0, bits, 0, width);
89                         for (int i = 1; i < inputs.size(); i++)
90                                 Bit.join(bits, inputs.get(i).getInputValues().getBits());
91                 }
92                 bitsWithoutFusions = bits;
93                 if (fusedBits == null)
94                         setNewValues(BitVector.of(bits));
95                 else
96                         invalidateCachedValuesForAllFusedWires();
97         }
98
99         private void recalculatedCachedValues()
100         {
101                 Bit[] bits;
102                 if (fusedBits == null)
103                         bits = bitsWithoutFusions;
104                 else
105                 {
106                         bits = new Bit[width];
107                         for (int i = 0; i < width; i++)
108                         {
109                                 FusedBit fusion = fusedBits[i];
110                                 if (fusion == null)
111                                         bits[i] = bitsWithoutFusions[i];
112                                 else
113                                         bits[i] = fusion.getValue();
114                         }
115                 }
116                 cachedValues = BitVector.of(bits);
117         }
118
119         /**
120          * Forces a Wire to take on specific values. If the new values differ from the old ones, the observers of the Wire will be notified.
121          * WARNING! Use this with care! The preferred way of writing the values is ReadWriteEnd.feedSignals(BitVector)
122          * 
123          * @param values The values the <code>Wire</code> will have immediately after this method is called
124          */
125         public void forceValues(BitVector values)
126         {
127                 bitsWithoutFusions = values.getBits();
128                 invalidateCachedValuesForAllFusedWires();
129                 notifyObservers();
130         }
131
132         /**
133          * Returns the least significant bit (LSB)
134          */
135         public Bit getValue()
136         {
137                 return getValue(0);
138         }
139
140         /**
141          * Returns the least significant bit (LSB) of the given index
142          */
143         public Bit getValue(int index)
144         {
145                 return getValues().getLSBit(index);
146         }
147
148         public BitVector getValues(int start, int end)
149         {
150                 return getValues().subVector(start, end);
151         }
152
153         public BitVector getValues()
154         {
155                 if (cachedValues == null)
156                         recalculatedCachedValues();
157                 return cachedValues;
158         }
159
160         /**
161          * Adds an {@link LogicObserver}, who will be notified when the value of the {@link CoreWire} is updated.
162          * 
163          * @param ob The {@link LogicObserver} to be notified of changes.
164          * @return true if the given {@link LogicObserver} was not already registered, false otherwise
165          * 
166          * @author Fabian Stemmler
167          */
168         boolean attachEnd(ReadEnd end)
169         {
170                 return attached.add(end);
171         }
172
173         void detachEnd(ReadEnd end)
174         {
175                 attached.remove(end);
176         }
177
178         private void notifyObservers()
179         {
180                 attached.forEach(ReadEnd::update);
181         }
182
183         /**
184          * Create and register a {@link ReadWriteEnd} object, which is tied to this {@link CoreWire}. This {@link ReadWriteEnd} can be written
185          * to.
186          */
187         public ReadWriteEnd createReadWriteEnd()
188         {
189                 return new ReadWriteEnd();
190         }
191
192         /**
193          * Create a {@link ReadEnd} object, which is tied to this {@link CoreWire}. This {@link ReadEnd} cannot be written to.
194          */
195         public ReadEnd createReadOnlyEnd()
196         {
197                 return new ReadEnd();
198         }
199
200         void registerInput(ReadWriteEnd toRegister)
201         {
202                 inputs.add(toRegister);
203                 recalculateValuesWithoutFusions();
204         }
205
206         /**
207          * A {@link ReadEnd} feeds a constant signal into the {@link CoreWire} it is tied to. The combination of all inputs determines the
208          * {@link CoreWire}s final value. X dominates all other inputs Z does not affect the final value, unless there are no other inputs than
209          * Z 0 and 1 turn into X when they are mixed
210          * 
211          * @author Fabian Stemmler
212          */
213         public class ReadEnd implements LogicObservable
214         {
215                 private List<LogicObserver> observers = new ArrayList<>();
216
217                 ReadEnd()
218                 {
219                         super();
220                         CoreWire.this.attachEnd(this);
221                 }
222
223                 public void update()
224                 {
225                         notifyObservers();
226                 }
227
228                 /**
229                  * Included for convenient use on {@link CoreWire}s of width 1.
230                  * 
231                  * @return The value of bit 0.
232                  * 
233                  * @author Fabian Stemmler
234                  */
235                 public Bit getValue()
236                 {
237                         return CoreWire.this.getValue();
238                 }
239
240                 /**
241                  * @param index Index of the requested bit.
242                  * @return The value of the indexed bit.
243                  * 
244                  * @author Fabian Stemmler
245                  */
246                 public Bit getValue(int index)
247                 {
248                         return CoreWire.this.getValue(index);
249                 }
250
251                 public BitVector getValues()
252                 {
253                         return CoreWire.this.getValues();
254                 }
255
256                 /**
257                  * @param start Start of the wanted segment. (inclusive)
258                  * @param end   End of the wanted segment. (exclusive)
259                  * @return The values of the segment of {@link Bit}s indexed.
260                  * 
261                  * @author Fabian Stemmler
262                  */
263                 public BitVector getValues(int start, int end)
264                 {
265                         return CoreWire.this.getValues(start, end);
266                 }
267
268                 @Override
269                 public String toString()
270                 {
271                         return CoreWire.this.toString();
272                 }
273
274                 public void close()
275                 {
276                         inputs.remove(this);
277                         detachEnd(this);
278                         recalculateValuesWithoutFusions();
279                 }
280
281                 public int width()
282                 {
283                         return width;
284                 }
285
286                 public CoreWire getWire()
287                 {
288                         return CoreWire.this;
289                 }
290
291                 @Override
292                 public void registerObserver(LogicObserver ob)
293                 {
294                         observers.add(ob);
295                 }
296
297                 @Override
298                 public void deregisterObserver(LogicObserver ob)
299                 {
300                         observers.remove(ob);
301                 }
302
303 //              void registerCloseObserver(LogicObserver ob)
304 //              {
305 //                      closeObserver.add(ob);
306 //              }
307 //              
308 //              void deregisterCloseObserver(LogicObserver ob)
309 //              {
310 //                      closeObserver.remove(ob);
311 //              }
312
313                 @Override
314                 public void notifyObservers()
315                 {
316                         observers.forEach(ob -> ob.update(this));
317                 }
318         }
319
320         public class ReadWriteEnd extends ReadEnd
321         {
322                 private boolean open;
323                 private boolean isWriting;
324                 private BitVector inputValues;
325
326                 ReadWriteEnd()
327                 {
328                         super();
329                         open = true;
330                         isWriting = true;
331                         initValues();
332                         registerInput(this);
333                 }
334
335                 private void initValues()
336                 {
337                         inputValues = U.toVector(width);
338                 }
339
340                 /**
341                  * Sets the wires values. This takes up time, as specified by the {@link CoreWire}s travel time.
342                  * 
343                  * @param newValues The new values the wires should take on.
344                  * 
345                  * @author Fabian Stemmler
346                  */
347                 public void feedSignals(Bit... newValues)
348                 {
349                         feedSignals(BitVector.of(newValues));
350                 }
351
352                 // TODO what if this is called multiple times at the same simulation time? (happens in component unit tests)
353                 public void feedSignals(BitVector newValues)
354                 {
355                         if (newValues.length() != width)
356                                 throw new IllegalArgumentException(
357                                                 String.format("Attempted to input %d bits instead of %d bits.", newValues.length(), width));
358                         if (!open)
359                                 throw new IllegalStateException("Attempted to write to closed WireArrayEnd.");
360                         timeline.addEvent(e -> setValues(newValues), travelTime);
361                 }
362
363                 /**
364                  * Sets values of a subarray of wires. This takes up time, as specified by the {@link CoreWire}s travel time.
365                  * 
366                  * @param bitVector   The new values the wires should take on.
367                  * @param startingBit The first index of the subarray of wires.
368                  * 
369                  * @author Fabian Stemmler
370                  */
371                 public void feedSignals(int startingBit, BitVector bitVector)
372                 {
373                         if (!open)
374                                 throw new IllegalStateException("Attempted to write to closed WireArrayEnd.");
375                         timeline.addEvent(e -> setValues(startingBit, bitVector), travelTime);
376                 }
377
378                 /**
379                  * Sets the values that are being fed into the {@link CoreWire}. The preferred way of setting {@link ReadWriteEnd} values is via
380                  * feedValues(...) with a delay.
381                  */
382                 void setValues(int startingBit, BitVector newValues)
383                 {
384                         // index check covered in equals
385                         if (!inputValues.equalsWithOffset(newValues, startingBit))
386                         {
387                                 Bit[] vals = inputValues.getBits();
388                                 System.arraycopy(newValues.getBits(), 0, vals, startingBit, newValues.length());
389                                 inputValues = BitVector.of(vals);
390                                 CoreWire.this.recalculateValuesWithoutFusions();
391                         }
392                 }
393
394                 /**
395                  * Sets the values that are being fed into the {@link CoreWire}. The preferred way of setting {@link ReadWriteEnd} values is via
396                  * feedValues(...) with a delay.
397                  */
398                 void setValues(BitVector newValues)
399                 {
400                         if (inputValues.equals(newValues))
401                                 return;
402                         inputValues = newValues;
403                         CoreWire.this.recalculateValuesWithoutFusions();
404                 }
405
406                 /**
407                  * @return The value (of bit 0) the {@link ReadEnd} is currently feeding into the associated {@link CoreWire}.Returns the least
408                  *         significant bit (LSB)
409                  */
410                 public Bit getInputValue()
411                 {
412                         return getInputValue(0);
413                 }
414
415                 /**
416                  * @return The value which the {@link ReadEnd} is currently feeding into the associated {@link CoreWire} at the indexed {@link Bit}.
417                  *         Returns the least significant bit (LSB)
418                  * 
419                  */
420                 public Bit getInputValue(int index)
421                 {
422                         return inputValues.getLSBit(index);
423                 }
424
425                 /**
426                  * @return A copy (safe to modify) of the values the {@link ReadEnd} is currently feeding into the associated {@link CoreWire}.
427                  */
428                 public BitVector getInputValues()
429                 {
430                         return inputValues;
431                 }
432
433                 public BitVector getInputValues(int start, int end)
434                 {
435                         return inputValues.subVector(start, end);
436                 }
437
438                 /**
439                  * {@link ReadEnd} now feeds Z into the associated {@link CoreWire}.
440                  */
441                 public void clearSignals()
442                 {
443                         feedSignals(Z.toVector(width));
444                 }
445
446                 public BitVector wireValuesExcludingMe()
447                 {
448                         BitVectorMutator mutator = BitVectorMutator.empty();
449                         boolean modified = false;
450                         for (ReadWriteEnd wireEnd : inputs)
451                         {
452                                 if (wireEnd == this)
453                                         continue;
454                                 modified = true;
455                                 mutator.join(wireEnd.inputValues);
456                         }
457                         if (!modified)
458                                 mutator.join(BitVector.of(Bit.Z, width));
459                         return mutator.toBitVector();
460                 }
461
462                 @Override
463                 public String toString()
464                 {
465                         return inputValues.toString();
466                 }
467
468                 @Override
469                 public void close()
470                 {
471                         super.close();
472                         open = false;
473                 }
474
475                 void setWriting(boolean isWriting)
476                 {
477                         if (this.isWriting != isWriting)
478                         {
479                                 this.isWriting = isWriting;
480                                 if (isWriting)
481                                         inputs.add(this);
482                                 else
483                                         inputs.remove(this);
484                                 CoreWire.this.recalculateValuesWithoutFusions();
485                         }
486                 }
487
488                 boolean isWriting()
489                 {
490                         return isWriting;
491                 }
492         }
493
494         @Override
495         public String toString()
496         {
497                 String name = this.name == null ? String.format("0x%08x", hashCode()) : this.name;
498                 return String.format("wire %s value: %s inputs: %s", name, getValues(), inputs);
499         }
500
501         public static ReadEnd[] extractEnds(CoreWire[] w)
502         {
503                 ReadEnd[] inputs = new ReadEnd[w.length];
504                 for (int i = 0; i < w.length; i++)
505                         inputs[i] = w[i].createReadWriteEnd();
506                 return inputs;
507         }
508
509         /**
510          * 
511          * Fuses two wires together. If the bits change in one Wire, the other is changed accordingly immediately. Warning: The bits are
512          * permanently fused together.
513          * 
514          * @param a The {@link CoreWire} to be fused with b
515          * @param b The {@link CoreWire} to be fused with a
516          */
517         public static void fuse(CoreWire a, CoreWire b)
518         {
519                 fuse(a, b, 0, 0, a.width);
520         }
521
522         /**
523          * Fuses the selected bits of two wires together. If the bits change in one Wire, the other is changed accordingly immediately. Warning:
524          * The bits are permanently fused together.
525          * 
526          * @param a     The {@link CoreWire} to be (partially) fused with b
527          * @param b     The {@link CoreWire} to be (partially) fused with a
528          * @param fromA The first bit of {@link CoreWire} a to be fused
529          * @param fromB The first bit of {@link CoreWire} b to be fused
530          * @param width The amount of bits to fuse
531          */
532         public static void fuse(CoreWire a, CoreWire b, int fromA, int fromB, int width)
533         {
534                 // iterate in this direction to be fail-fast (rely on the checks in fuse(Wire, Wire, int, int)
535                 for (int i = width - 1; i >= 0; i--)
536                         fuse(a, b, fromA + i, fromB + i);
537         }
538
539         /**
540          * Fuses one bit of two wires together. If this bit changes in one Wire, the other is changed accordingly immediately. Warning: The bits
541          * are permanently fused together.
542          * 
543          * @param a    The {@link CoreWire} to be (partially) fused with b
544          * @param b    The {@link CoreWire} to be (partially) fused with a
545          * @param bitA The bit of {@link CoreWire} a to be fused
546          * @param bitB The bit of {@link CoreWire} b to be fused
547          */
548         public static void fuse(CoreWire a, CoreWire b, int bitA, int bitB)
549         {
550                 if (bitA >= a.width)
551                         throw new IllegalArgumentException("No bit " + bitA + " in " + a + " (width " + a.width + ")");
552                 if (bitB >= b.width)
553                         throw new IllegalArgumentException("No bit " + bitB + " in " + b + " (width " + b.width + ")");
554                 if (a.fusedBits == null)
555                         a.fusedBits = new FusedBit[a.width];
556                 if (b.fusedBits == null)
557                         b.fusedBits = new FusedBit[b.width];
558                 FusedBit oldFusionA = a.fusedBits[bitA];
559                 FusedBit oldFusionB = b.fusedBits[bitB];
560                 if (oldFusionA == null)
561                         if (oldFusionB == null)
562                         {
563                                 FusedBit fusion = new FusedBit();
564                                 fusion.addParticipatingWireBit(a, bitA);
565                                 fusion.addParticipatingWireBit(b, bitB);
566                         } else
567                                 oldFusionB.addParticipatingWireBit(a, bitA);
568                 else if (oldFusionB == null)
569                         oldFusionA.addParticipatingWireBit(b, bitB);
570                 else
571                         oldFusionA.mergeOtherIntoThis(oldFusionB);
572         }
573
574         private static class FusedBit
575         {
576                 private final Set<WireBit> participatingWireBits;
577
578                 public FusedBit()
579                 {
580                         this.participatingWireBits = new HashSet<>();
581                 }
582
583                 public void addParticipatingWireBit(CoreWire w, int bit)
584                 {
585                         addParticipatingWireBit(new WireBit(w, bit));
586                 }
587
588                 private void addParticipatingWireBit(WireBit wb)
589                 {
590                         wb.wire.fusedBits[wb.bit] = this;
591                         participatingWireBits.add(wb);
592                         wb.wire.invalidateCachedValuesForAllFusedWires();
593                 }
594
595                 public void mergeOtherIntoThis(FusedBit other)
596                 {
597                         for (WireBit wb : other.participatingWireBits)
598                                 addParticipatingWireBit(wb);
599                 }
600
601                 public void invalidateCachedValuesForAllParticipatingWires()
602                 {
603                         for (WireBit wb : participatingWireBits)
604                                 wb.wire.invalidateCachedValues();
605                 }
606
607                 public Bit getValue()
608                 {
609                         Bit result = null;
610                         for (WireBit wb : participatingWireBits)
611                                 if (!wb.wire.inputs.isEmpty())
612                                 {
613                                         Bit bit = wb.wire.bitsWithoutFusions[wb.bit];
614                                         result = result == null ? bit : result.join(bit);
615                                 }
616                         return result == null ? U : result;
617                 }
618         }
619
620         private static class WireBit
621         {
622                 public final CoreWire wire;
623                 public final int bit;
624
625                 public WireBit(CoreWire wire, int bit)
626                 {
627                         this.wire = wire;
628                         this.bit = bit;
629                 }
630
631                 @Override
632                 public int hashCode()
633                 {
634                         final int prime = 31;
635                         int result = 1;
636                         result = prime * result + bit;
637                         result = prime * result + ((wire == null) ? 0 : wire.hashCode());
638                         return result;
639                 }
640
641                 @Override
642                 public boolean equals(Object obj)
643                 {
644                         if (this == obj)
645                                 return true;
646                         if (obj == null)
647                                 return false;
648                         if (getClass() != obj.getClass())
649                                 return false;
650                         WireBit other = (WireBit) obj;
651                         if (bit != other.bit)
652                                 return false;
653                         if (wire == null)
654                         {
655                                 if (other.wire != null)
656                                         return false;
657                         } else if (!wire.equals(other.wire))
658                                 return false;
659                         return true;
660                 }
661         }
662 }