aboutsummaryrefslogtreecommitdiff
path: root/src/test/scala/firrtlTests/annotationTests/MorphismSpec.scala
blob: 02b03729cbf49a051ded93ae1cc5ac295c428d48 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
// SPDX-License-Identifier: Apache-2.0

package firrtlTests.annotationTests

import firrtl._
import firrtl.annotations.{Annotation, CircuitTarget, CompleteTarget, DeletedAnnotation}
import firrtl.annotations.transforms.{DupedResult, ResolvePaths}
import firrtl.transforms.DedupedResult
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should._

class MorphismSpec extends AnyFlatSpec with Matchers {

  object AnAnnotation {
    def apply(target: CompleteTarget) = new AnAnnotation(Some(target))
  }

  case class AnAnnotation(
    target: Option[CompleteTarget],
    from:   Option[AnAnnotation] = None,
    cause:  Option[String] = None)
      extends Annotation {
    override def update(renames: RenameMap): Seq[AnAnnotation] = {
      if (target.isDefined) {
        renames.get(target.get) match {
          case None          => Seq(this)
          case Some(Seq())   => Seq(AnAnnotation(None, Some(this)))
          case Some(targets) =>
            //TODO: Add cause of renaming, requires FIRRTL change to RenameMap
            targets.map { t => AnAnnotation(Some(t), Some(this)) }
        }
      } else Seq(this)
    }

    private def expand(stringBuilder: StringBuilder): StringBuilder = {
      if (target.isDefined) {
        stringBuilder.append(s"${target.get.serialize}")
      } else {
        stringBuilder.append(s"<DELETED>")
      }
      if (from.isDefined) {
        val arrow = cause.map("(" + _ + ")").getOrElse("")
        stringBuilder.append(s" <-$arrow- ")
        from.get.expand(stringBuilder)
      }
      stringBuilder
    }

    override def serialize: String = expand(new StringBuilder()).toString
  }

  object StripDeleted extends Transform {

    override def inputForm = UnknownForm

    override def outputForm = UnknownForm

    override def execute(a: CircuitState): CircuitState = {

      val annotationsx = a.annotations.filter {
        case a: DeletedAnnotation => false
        case AnAnnotation(None, _, _) => false
        case _: DupedResult   => false
        case _: DedupedResult => false
        case _ => true
      }

      a.copy(annotations = annotationsx)

    }

  }

  trait CircuitFixture {

    /** An input FIRRTL string */
    val input: String

    lazy val output: String = input

    /** Input annotations */
    val annotations: AnnotationSeq = Seq.empty

    val finalAnnotations: Option[AnnotationSeq] = None

    lazy val state = CircuitState(Parser.parse(input), UnknownForm, annotations)
  }

  trait RightInverseFixture extends CircuitFixture {

    /** An endomorphism i.e. a function mapping from CircuitState to CircuitState */
    val f: Seq[Transform]

    /** The right inverse of f */
    val g: Seq[Transform]

    val setup: Seq[Transform] = Seq(
      firrtl.passes.ToWorkingIR,
      new firrtl.ResolveAndCheck
    )

    val cleanup: Seq[Transform] = Seq(
      StripDeleted
    )

    def apply(a: CircuitState): CircuitState = {
      val ax = (setup ++ f ++ g).foldLeft(a) {
        case (state, transform) => transform.runTransform(state)
      }

      cleanup.foldLeft(ax) {
        case (state, transform) => transform.transform(state)
      }
    }

    lazy val outputState = apply(state)

    def test(): Unit = {

      /* The output circuit should be the same as the input circuit */
      outputState.circuit.serialize should be(Parser.parse(output).serialize)
      info("the circuits are the same")
      info(state.circuit.serialize)

      /* The output annotations should match the input annotations */
      info(s"Input annotations:\n\t${state.annotations.toList.mkString("\n\t")}")
      info(s"Output annotations:\n\t${outputState.annotations.toList.mkString("\n\t")}")
      if (finalAnnotations.nonEmpty) {
        info(s"Final annotations:\n\t${finalAnnotations.get.toList.mkString("\n\t")}")
      }

      info(s"Output Annotation History:\n")
      outputState.annotations.collect {
        case a: AnAnnotation => info(a.serialize)
      }

      val inputAnnotations = state.annotations.filter {
        case r: ResolvePaths => false
        case other => true
      }

      if (finalAnnotations.isEmpty) {
        outputState.annotations.size should be(inputAnnotations.size)
        info("the number of annotations is the same")

        outputState.annotations.zip(inputAnnotations).collect {
          case (a: AnAnnotation, b: AnAnnotation) => a.target should be(b.target)
        }
        info("each annotation is the same")
      } else {
        outputState.annotations.zip(finalAnnotations.get).collect {
          case (a: AnAnnotation, b: AnAnnotation) => a.target should be(b.target)
        }

        outputState.annotations.size should be(finalAnnotations.get.size)
        info("the number of annotations is the same")

        info("each annotation is the same as the final annotations")
      }
    }

  }

  trait IdempotencyFixture extends CircuitFixture {

    /** An endomorphism */
    val f: Seq[Transform]

    val setup: Seq[Transform] = Seq(
      firrtl.passes.ToWorkingIR,
      new firrtl.ResolveAndCheck
    )

    val cleanup: Seq[Transform] = Seq(
      StripDeleted
    )

    def apply(a: CircuitState): (CircuitState, CircuitState) = {

      val once = (setup ++ f).foldLeft(a) {
        case (state, transform) => transform.runTransform(state)
      }

      val twice = f.foldLeft(once) {
        case (state, transform) => transform.runTransform(state)
      }

      val onceClean = cleanup.foldLeft(once) {
        case (state, transform) => transform.transform(state)
      }

      val twiceClean = cleanup.foldLeft(twice) {
        case (state, transform) => transform.transform(state)
      }

      (onceClean, twiceClean)

    }

    lazy val (oneApplication, twoApplications) = apply(state)

    def test(): Unit = {

      info("a second application does not change the circuit")
      twoApplications.circuit.serialize should be(oneApplication.circuit.serialize)

      info("each annotation is the same after a second application")
      twoApplications.annotations.zip(oneApplication.annotations).foreach {
        case (a, b) => a should be(b)
      }

      info("the number of annotations after a second application is the same")
      twoApplications.annotations.size should be(oneApplication.annotations.size)

    }

  }

  trait DefaultExample extends CircuitFixture {
    override val input =
      """|circuit Top:
         |  module Foo:
         |    node a = UInt<1>(0)
         |  module Bop:
         |    node a = UInt<1>(0)
         |  module Fub:
         |    node a = UInt<1>(0)
         |  module Bar:
         |    node a = UInt<1>(0)
         |  module Baz:
         |    input x: UInt<1>
         |    inst foo of Foo
         |    inst bar of Bar
         |  module Qux:
         |    input x: UInt<1>
         |    inst foo of Fub
         |    inst bar of Bop
         |  module Top:
         |    inst baz of Baz
         |    inst qux of Qux""".stripMargin

    def deduped =
      """|circuit Top:
         |  module Foo:
         |    node a = UInt<1>(0)
         |  module Baz:
         |    input x: UInt<1>
         |    inst foo of Foo
         |    inst bar of Foo
         |  module Top:
         |    inst baz of Baz
         |    inst qux of Baz""".stripMargin

    def allModuleInstances =
      IndexedSeq(
        CircuitTarget("Top").module("Foo"),
        CircuitTarget("Top").module("Bar"),
        CircuitTarget("Top").module("Fub"),
        CircuitTarget("Top").module("Bop"),
        CircuitTarget("Top").module("Baz"),
        CircuitTarget("Top").module("Qux"),
        CircuitTarget("Top").module("Top")
      )

    def allAbsoluteInstances =
      IndexedSeq(
        CircuitTarget("Top").module("Top").instOf("baz", "Baz").instOf("foo", "Foo"),
        CircuitTarget("Top").module("Top").instOf("baz", "Baz").instOf("bar", "Bar"),
        CircuitTarget("Top").module("Top").instOf("qux", "Qux").instOf("foo", "Fub"),
        CircuitTarget("Top").module("Top").instOf("qux", "Qux").instOf("bar", "Bop"),
        CircuitTarget("Top").module("Top").instOf("baz", "Baz"),
        CircuitTarget("Top").module("Top").instOf("qux", "Qux"),
        CircuitTarget("Top").module("Top")
      )

    def allRelative2LevelInstances =
      IndexedSeq(
        CircuitTarget("Top").module("Baz").instOf("foo", "Foo"),
        CircuitTarget("Top").module("Baz").instOf("bar", "Bar"),
        CircuitTarget("Top").module("Qux").instOf("foo", "Fub"),
        CircuitTarget("Top").module("Qux").instOf("bar", "Bop"),
        CircuitTarget("Top").module("Top").instOf("baz", "Baz"),
        CircuitTarget("Top").module("Top").instOf("qux", "Qux"),
        CircuitTarget("Top").module("Top")
      )

    def allDedupedAbsoluteInstances =
      IndexedSeq(
        CircuitTarget("Top").module("Top").instOf("baz", "Baz").instOf("foo", "Foo"),
        CircuitTarget("Top").module("Top").instOf("baz", "Baz").instOf("bar", "Foo"),
        CircuitTarget("Top").module("Top").instOf("qux", "Baz").instOf("foo", "Foo"),
        CircuitTarget("Top").module("Top").instOf("qux", "Baz").instOf("bar", "Foo"),
        CircuitTarget("Top").module("Top").instOf("baz", "Baz"),
        CircuitTarget("Top").module("Top").instOf("qux", "Baz"),
        CircuitTarget("Top").module("Top")
      )
  }

  behavior.of("EliminateTargetPaths")

  // NOTE: equivalience is defined structurally in this case
  trait RightInverseEliminateTargetsFixture extends RightInverseFixture with DefaultExample {
    override val f: Seq[Transform] = Seq(new firrtl.transforms.DedupModules)
    override val g: Seq[Transform] = Seq(new firrtl.annotations.transforms.EliminateTargetPaths)
  }
  trait IdempotencyEliminateTargetsFixture extends IdempotencyFixture with DefaultExample {
    override val f: Seq[Transform] = Seq(new firrtl.annotations.transforms.EliminateTargetPaths)
  }

  it should "invert DedupModules with no annotations" in new RightInverseEliminateTargetsFixture {
    override val annotations: AnnotationSeq = Seq(
      ResolvePaths(allAbsoluteInstances)
    )
    test()
  }

  it should "invert DedupModules with absolute InstanceTarget annotations" in new RightInverseEliminateTargetsFixture {
    override val annotations: AnnotationSeq =
      allAbsoluteInstances.map(AnAnnotation(_)) :+ ResolvePaths(allAbsoluteInstances)

    override val finalAnnotations: Option[AnnotationSeq] = Some(
      allModuleInstances.map(AnAnnotation.apply)
    )
    test()
  }

  it should "invert DedupModules with all ModuleTarget annotations" in new RightInverseEliminateTargetsFixture {
    override val annotations: AnnotationSeq =
      allModuleInstances.map(AnAnnotation.apply) :+ ResolvePaths(allAbsoluteInstances)
    test()
  }

  it should "invert DedupModules with relative InstanceTarget annotations" in new RightInverseEliminateTargetsFixture {
    override val annotations: AnnotationSeq =
      allRelative2LevelInstances.map(AnAnnotation.apply) :+ ResolvePaths(allAbsoluteInstances)

    override val finalAnnotations: Option[AnnotationSeq] = Some(
      allModuleInstances.map(AnAnnotation.apply)
    )
    test()
  }

  it should "invert DedupModules with a ReferenceTarget annotation" in new RightInverseEliminateTargetsFixture {
    override val annotations: AnnotationSeq = Seq(
      AnAnnotation(CircuitTarget("Top").module("Top").ref("x")),
      ResolvePaths(allAbsoluteInstances)
    )
    test()
  }

  it should "invert DedupModules with partially duplicated modules" in new RightInverseEliminateTargetsFixture {
    override val input =
      """|circuit Top:
         |  module Foo:
         |    node a = UInt<1>(0)
         |  module Bar:
         |    node a = UInt<1>(0)
         |  module Baz:
         |    input x: UInt<1>
         |    inst foo of Foo
         |    inst foox of Foo
         |    inst bar of Bar
         |  module Top:
         |    inst baz of Baz
         |    inst qux of Baz""".stripMargin
    override lazy val output =
      """|circuit Top :
         |  module Foo___Top_baz_bar :
         |    node a = UInt<1>("h0")
         |  module Foo___Top_qux_foox :
         |    node a = UInt<1>("h0")
         |  module Foo___Top_qux_bar :
         |    node a = UInt<1>("h0")
         |  module Foo___Top_baz_foox :
         |    node a = UInt<1>("h0")
         |  module Foo___Top_baz_foo :
         |    node a = UInt<1>("h0")
         |  module Foo___Top_qux_foo :
         |    node a = UInt<1>("h0")
         |  module Baz___Top_baz :
         |    input x : UInt<1>
         |    inst foo of Foo___Top_baz_foo
         |    inst foox of Foo___Top_baz_foox
         |    inst bar of Foo___Top_baz_bar
         |  module Baz___Top_qux :
         |    input x : UInt<1>
         |    inst foo of Foo___Top_qux_foo
         |    inst foox of Foo___Top_qux_foox
         |    inst bar of Foo___Top_qux_bar
         |  module Top :
         |    inst baz of Baz___Top_baz
         |    inst qux of Baz___Top_qux""".stripMargin
    override val annotations: AnnotationSeq = Seq(
      AnAnnotation(CircuitTarget("Top").module("Baz").instOf("foo", "Foo")),
      ResolvePaths(
        Seq(
          CircuitTarget("Top").module("Top").instOf("baz", "Baz").instOf("foo", "Foo"),
          CircuitTarget("Top").module("Top").instOf("baz", "Baz").instOf("foox", "Foo"),
          CircuitTarget("Top").module("Top").instOf("baz", "Baz").instOf("bar", "Bar"),
          CircuitTarget("Top").module("Top").instOf("qux", "Baz").instOf("foo", "Foo"),
          CircuitTarget("Top").module("Top").instOf("qux", "Baz").instOf("foox", "Foo"),
          CircuitTarget("Top").module("Top").instOf("qux", "Baz").instOf("bar", "Bar")
        )
      )
    )

    override val finalAnnotations: Option[AnnotationSeq] = Some(
      Seq(
        AnAnnotation(CircuitTarget("Top").module("Foo___Top_qux_foo")),
        AnAnnotation(CircuitTarget("Top").module("Foo___Top_baz_foo"))
      )
    )
    test()
  }

  it should "be idempotent with per-module annotations" in new IdempotencyEliminateTargetsFixture {

    /** An endomorphism */
    override val annotations: AnnotationSeq =
      allModuleInstances.map(AnAnnotation.apply) :+ ResolvePaths(allAbsoluteInstances)
    test()
  }

  it should "be idempotent with per-instance annotations" in new IdempotencyEliminateTargetsFixture {

    /** An endomorphism */
    override val annotations: AnnotationSeq =
      allAbsoluteInstances.map(AnAnnotation.apply) :+ ResolvePaths(allAbsoluteInstances)
    test()
  }

  it should "be idempotent with relative module annotations" in new IdempotencyEliminateTargetsFixture {

    /** An endomorphism */
    override val annotations: AnnotationSeq =
      allRelative2LevelInstances.map(AnAnnotation.apply) :+ ResolvePaths(allAbsoluteInstances)
    test()
  }

  behavior.of("DedupModules")

  trait RightInverseDedupModulesFixture extends RightInverseFixture with DefaultExample {
    override val f: Seq[Transform] = Seq(new firrtl.annotations.transforms.EliminateTargetPaths)
    override val g: Seq[Transform] = Seq(new firrtl.transforms.DedupModules)
  }

  trait IdempotencyDedupModulesFixture extends IdempotencyFixture with DefaultExample {
    override val f: Seq[Transform] = Seq(new firrtl.transforms.DedupModules)
  }

  it should "invert EliminateTargetPaths with no annotations" in new RightInverseDedupModulesFixture {
    override val annotations: AnnotationSeq = Seq(
      ResolvePaths(allAbsoluteInstances)
    )
    override lazy val output = deduped

    test()
  }

  it should "invert EliminateTargetPaths with absolute InstanceTarget annotations" in new RightInverseDedupModulesFixture {
    override val annotations: AnnotationSeq =
      allAbsoluteInstances.map(AnAnnotation(_)) :+ ResolvePaths(allAbsoluteInstances)
    override val finalAnnotations: Option[AnnotationSeq] = Some(allDedupedAbsoluteInstances.map(AnAnnotation.apply))
    override lazy val output = deduped
    test()
  }

  it should "invert EliminateTargetPaths with all ModuleTarget annotations" in new RightInverseDedupModulesFixture {
    override val annotations: AnnotationSeq =
      allModuleInstances.map(AnAnnotation.apply) :+ ResolvePaths(allAbsoluteInstances)
    override val finalAnnotations: Option[AnnotationSeq] = Some(
      allDedupedAbsoluteInstances.map(AnAnnotation.apply)
    )
    override lazy val output = deduped
    test()
  }

  it should "invert EliminateTargetPaths with partially duplicated modules" in new RightInverseDedupModulesFixture {
    override val input =
      """|circuit Top:
         |  module Foo:
         |    node a = UInt<1>(0)
         |  module Bar:
         |    node a = UInt<1>(0)
         |  module Baz:
         |    input x: UInt<1>
         |    inst foo of Foo
         |    inst foox of Foo
         |    inst bar of Bar
         |  module Top:
         |    inst baz of Baz
         |    inst qux of Baz""".stripMargin
    override lazy val output =
      """|circuit Top :
         |  module Foo :
         |    node a = UInt<1>("h0")
         |  module Baz :
         |    input x : UInt<1>
         |    inst foo of Foo
         |    inst foox of Foo
         |    inst bar of Foo
         |  module Top :
         |    inst baz of Baz
         |    inst qux of Baz""".stripMargin
    override val annotations: AnnotationSeq = Seq(
      AnAnnotation(CircuitTarget("Top").module("Baz").instOf("foo", "Foo")),
      ResolvePaths(
        Seq(
          CircuitTarget("Top").module("Top").instOf("baz", "Baz").instOf("foo", "Foo"),
          CircuitTarget("Top").module("Top").instOf("baz", "Baz").instOf("foox", "Foo"),
          CircuitTarget("Top").module("Top").instOf("baz", "Baz").instOf("bar", "Bar"),
          CircuitTarget("Top").module("Top").instOf("qux", "Baz").instOf("foo", "Foo"),
          CircuitTarget("Top").module("Top").instOf("qux", "Baz").instOf("foox", "Foo"),
          CircuitTarget("Top").module("Top").instOf("qux", "Baz").instOf("bar", "Bar")
        )
      )
    )

    override val finalAnnotations: Option[AnnotationSeq] = Some(
      Seq(
        AnAnnotation(CircuitTarget("Top").module("Top").instOf("baz", "Baz").instOf("foo", "Foo")),
        AnAnnotation(CircuitTarget("Top").module("Top").instOf("qux", "Baz").instOf("foo", "Foo"))
      )
    )
    test()
  }

  it should "be idempotent with per-module annotations" in new IdempotencyDedupModulesFixture {

    /** An endomorphism */
    override val annotations: AnnotationSeq =
      allModuleInstances.map(AnAnnotation.apply) :+ ResolvePaths(allAbsoluteInstances)
    test()
  }

  it should "be idempotent with per-instance annotations" in new IdempotencyDedupModulesFixture {

    /** An endomorphism */
    override val annotations: AnnotationSeq =
      allAbsoluteInstances.map(AnAnnotation.apply) :+ ResolvePaths(allAbsoluteInstances)
    test()
  }

  it should "be idempotent with relative module annotations" in new IdempotencyDedupModulesFixture {

    /** An endomorphism */
    override val annotations: AnnotationSeq =
      allRelative2LevelInstances.map(AnAnnotation.apply) :+ ResolvePaths(allAbsoluteInstances)
    test()
  }

  /*
  //TODO: Future tests of GroupComponents + InlineInstances renaming
  behavior of "GroupComponents"
  it should "invert InlineInstances with not annotations" in (pending)
  it should "invert InlineInstances with InstanceTarget annotations" in (pending)
  it should "invert InlineInstances with a ModuleTarget annotation" in (pending)
  it should "invert InlineInstances with a ReferenceTarget annotation" in (pending)
  it should "be idempotent" in (pending)

  behavior of "InlineInstances"
  it should "invert GroupComponents with not annotations" in (pending)
  it should "invert GroupComponents with InstanceTarget annotations" in (pending)
  it should "invert GroupComponents with a ModuleTarget annotation" in (pending)
  it should "invert GroupComponents with a ReferenceTarget annotation" in (pending)
  it should "be idempotent" in (pending)
   */

}