aboutsummaryrefslogtreecommitdiff
path: root/src/main/scala/firrtl/Emitter.scala
diff options
context:
space:
mode:
authorSchuyler Eldridge2018-11-20 21:07:52 -0500
committerSchuyler Eldridge2019-04-25 16:24:08 -0400
commitb2dd0eb845081609d0aec4a873587ab3f22fe3f7 (patch)
tree1f8a89f48ebfeb6009f71ced42d8baf48078b09e /src/main/scala/firrtl/Emitter.scala
parentd0a7205d9e9ba02fb234eb70371012443deb242c (diff)
Add FirrtlStage, make Driver compatibility layer
This adds FirrtlStage, a reimplementation of the original FIRRTL Driver as a Stage. This updates the original firrtl.options package to implement FirrtlStage (namely, TransformLike is added) along with FirrtlMain. Finally, the original FIRRTL Driver is converted to a compatibility wrapper around FirrtlStage. For background, Stage and Phase form the basis of the Chisel/FIRRTL Hardware Compiler Framework (HCF). A Phase is a class that performs a mathematical transformation on an AnnotationSeq (in effect, a generalization of a FIRRTL transform). Curtly, a Stage is a Phase that also provides a user interface for generating annotations. By their construction, Phases are designed to be composed sequentially into a transformation pipeline. This modifies the existing options package (which provides Stage/Phase) to build out a type hierarchy around Stage/Phase. This adds TransformLike[A] which implements a mathematical transformation over some type A. Additionally, and as an interface between different TransformLikes, this adds Translator[A, B] which extends TransformLike[A], but does an internal transformation over type B. This is used to interface Phases with the existing FIRRTL compiler. This adds a runTransform method to Phase that, like Transform.runTransform, will automatically detect deleted Annotations and generate DeletedAnnotations. The new FirrtlStage, a reimplementation of FIRRTL's Driver, is added as a Stage composed of the following Phases: 1. AddDefaults - add default annotations 2. AddImplicitEmitter - adds an implicit emitter derived from the compiler 3. Checks - sanity check the AnnotationSeq 4. AddCircuit - convert FIRRTL input files/sources to circuits 5. AddImplicitOutputFile - add a default output file 6. Compiler - run the FIRRTL compiler 7. WriteEmitted - write any emitted modules/circuits to files The Driver is converted to a compatibility layer that replicates old Driver behavior. This is implemented by first using new toAnnotation methods for CommonOptions and FirrtlExecutionOptions that enable AnnotationSeq generation. Second, the generated AnnotationSeq is preprocessed and sent to FirrtlStage. The resulting Phase order is then: 1. AddImplicitAnnotationFile - adds a default annotation file 2. AddImplicitFirrtlFile - adds a default FIRRTL file using top name 3. AddImplicitOutputFile - adds an output file from top name 4. AddImplicitEmitter - adds a default emitter derived from a compiler and any split modules command line option 5. FirrtlStage - the aforementioned new FirrtlStage Finally, the output AnnotationSeq is then viewed as a FirrtlExecutionResult. This compatibility layer enables uninterrupted usage of old Driver infrastructure, e.g., FirrtlExecutionOptions and CommonOptions can still be mutated directly and used to run the Driver. This results in differing behavior between the new FirrtlStage and the old Driver, specifically: - FirrtlStage makes a clear delineation between a "compiler" and an "emitter". These are defined using separate options. A compiler is "-X/--compiler", while an emitter is one of "-E/--emit-circuit" or "-e/--emit-modules". - Related to the above, the "-fsm/--split-modules" has been removed from the FirrtlStage. This option is confusing once an implicit emitter is removed. It is also unclear how this should be handled once the user can specify multiple emitters, e.g., which emitter should "--split-modules" apply to? - WriteOutputAnnotations will, by default, not write DeletedAnnotations to the output file. - The old top name ("-tn/--top-name") option has been removed from FirrtlStage. This option is really a means to communicate what input and output files are as opposed to anything associated with the circuit name. This option is preserved for the Driver compatibility layer. Additionally, this changes existing transform scheduling to work for emitters (which subclass Transform). Previously, one emitter was explicitly scheduled at the end of all transforms for a given compiler. Additional emitters could be added, but they would be scheduled as transforms. This fixes this to rely on transform scheduling for all emitters. In slightly more detail: 1. The explicit emitter is removed from Compiler.compile 2. An explicit emitter is added to Compiler.compileAndEmit 3. Compiler.mergeTransforms will schedule emitters as late as possible, i.e., all emitters will occur after transforms that output their input form. 4. All AddImplicitEmitter phases (DriverCompatibility and normal) will add RunFirrtlTransformAnnotations to add implicit emitters The FIRRTL fat jar utilities are changed to point at FirrtlStage and not at the Driver. This has backwards incompatibility issues for users that are using the utilities directly, e.g., Rocket Chip. The Logger has been updated with methods for setting options based on an AnnotationSeq. This migrates the Logger to use AnnotationSeq as input parameters, e.g., for makeScope. Old-style methods are left in place and deprecated. However, the Logger is not itself a Stage. The options of Logger Annotations are included in the base Shell and Stage is updated to wrap its Phases in a Logger scope. Additionally, this changes any code that does option parsing to always prepend an annotation as opposed to appending an annotation. This is faster, but standardizing on this has implications for dealing with the parallel compilation annotation ordering. A Shell will now put the initial annotations first (in the order the user specified) and then place all annotations generating from parsing after that. This adds a test case to verify this behavior. Discovered custom transforms (via `RunFirrtlTransformAnnotation`s) are discovered by the compiler phase in a user-specified order, but are stored in reverse order to more efficiently prepend (as opposed to append) to a list. This now reverses the transform order before execution to preserve backwards compatibility of custom transform ordering. The Compiler phase also generates one deleted annotation for each `RunFirrtlTransformAnnotation`. These are also reversed. Miscellaneous small changes: - Split main method of Stage into StageMain class - Only mix in HasScoptOptions into Annotation companion objects (h/t @jackkoenig) - Store Compiler in CompilerAnnotation - CompilerNameAnnotation -> CompilerAnnotation - Make Emitter abstract in outputSuffix (move out of FirrtlOptions) - Add DriverCompatibility.AddImplicitOutputFile that will add an output file annotation based on the presence of a TopNameAnnotation. This is important for compatibility with the old Driver. - Cleanup Scaladoc - Refactor CircuitOption to be abstract in "toCircuit" that converts the option to a FirrtlCircuitAnnotation. This allows more of the conversion steps to be moved out of AddCircuit and into the actual annotation. - Add WriteDeletedAnnotation to module WriteOutputAnnotations - A method for accessing a FirrtlExecutionResultView is exposed in FIRRTL's DriverCompatibilityLayer - Using "--top-name/-tn" or "--split-modules/-fsm" with FirrtlStage generates an error indicating that this option is no longer supported - Using FirrtlStage without at least one emitter will generate a warning - Use vals for emitter in Compiler subclasses (these are used to build RunFirrtlTransformAnnotations and the object should be stable for comparisons) - Fixes to tests that use LowTransformSpec instead of MiddleTransformSpec. (SimpleTransformSpec is dumb and won't schedule transforms correctly. If you rely on an emitter, you need to use the right transform spec to test your transform if you're relying on an emitter.) Signed-off-by: Schuyler Eldridge <schuyler.eldridge@ibm.com>
Diffstat (limited to 'src/main/scala/firrtl/Emitter.scala')
-rw-r--r--src/main/scala/firrtl/Emitter.scala117
1 files changed, 91 insertions, 26 deletions
diff --git a/src/main/scala/firrtl/Emitter.scala b/src/main/scala/firrtl/Emitter.scala
index 7204eea6..44190b39 100644
--- a/src/main/scala/firrtl/Emitter.scala
+++ b/src/main/scala/firrtl/Emitter.scala
@@ -19,6 +19,9 @@ import firrtl.PrimOps._
import firrtl.WrappedExpression._
import Utils._
import MemPortUtils.{memPortField, memType}
+import firrtl.options.{HasScoptOptions, StageUtils, PhaseException}
+import firrtl.stage.RunFirrtlTransformAnnotation
+import scopt.OptionParser
// Datastructures
import scala.collection.mutable.{ArrayBuffer, LinkedHashMap, HashSet}
@@ -31,17 +34,70 @@ sealed trait EmitAnnotation extends NoTargetAnnotation {
case class EmitCircuitAnnotation(emitter: Class[_ <: Emitter]) extends EmitAnnotation
case class EmitAllModulesAnnotation(emitter: Class[_ <: Emitter]) extends EmitAnnotation
+object EmitCircuitAnnotation extends HasScoptOptions {
+ def addOptions(p: OptionParser[AnnotationSeq]): Unit = p
+ .opt[String]("emit-circuit")
+ .abbr("E")
+ .valueName("<chirrtl|high|middle|low|verilog|mverilog|sverilog>")
+ .unbounded()
+ .action{ (x, c) =>
+ val xx = x match {
+ case "chirrtl" => Seq(RunFirrtlTransformAnnotation(new ChirrtlEmitter),
+ EmitCircuitAnnotation(classOf[ChirrtlEmitter]))
+ case "high" => Seq(RunFirrtlTransformAnnotation(new HighFirrtlEmitter),
+ EmitCircuitAnnotation(classOf[HighFirrtlEmitter]))
+ case "middle" => Seq(RunFirrtlTransformAnnotation(new MiddleFirrtlEmitter),
+ EmitCircuitAnnotation(classOf[MiddleFirrtlEmitter]))
+ case "low" => Seq(RunFirrtlTransformAnnotation(new LowFirrtlEmitter),
+ EmitCircuitAnnotation(classOf[LowFirrtlEmitter]))
+ case "verilog" | "mverilog" => Seq(RunFirrtlTransformAnnotation(new VerilogEmitter),
+ EmitCircuitAnnotation(classOf[VerilogEmitter]))
+ case "sverilog" => Seq(RunFirrtlTransformAnnotation(new SystemVerilogEmitter),
+ EmitCircuitAnnotation(classOf[SystemVerilogEmitter]))
+ case _ => throw new PhaseException(s"Unknown emitter '$x'! (Did you misspell it?)")
+ }
+ xx ++ c }
+ .text("Run the specified circuit emitter (all modules in one file)")
+}
+
+object EmitAllModulesAnnotation extends HasScoptOptions {
+ def addOptions(p: OptionParser[AnnotationSeq]): Unit = p
+ .opt[String]("emit-modules")
+ .abbr("e")
+ .valueName("<none|high|middle|low|verilog|mverilog|sverilog>")
+ .unbounded()
+ .action{ (x, c) =>
+ val xx = x match {
+ case "chirrtl" => Seq(RunFirrtlTransformAnnotation(new ChirrtlEmitter),
+ EmitAllModulesAnnotation(classOf[ChirrtlEmitter]))
+ case "high" => Seq(RunFirrtlTransformAnnotation(new HighFirrtlEmitter),
+ EmitAllModulesAnnotation(classOf[HighFirrtlEmitter]))
+ case "middle" => Seq(RunFirrtlTransformAnnotation(new MiddleFirrtlEmitter),
+ EmitAllModulesAnnotation(classOf[MiddleFirrtlEmitter]))
+ case "low" => Seq(RunFirrtlTransformAnnotation(new LowFirrtlEmitter),
+ EmitAllModulesAnnotation(classOf[LowFirrtlEmitter]))
+ case "verilog" | "mverilog" => Seq(RunFirrtlTransformAnnotation(new VerilogEmitter),
+ EmitAllModulesAnnotation(classOf[VerilogEmitter]))
+ case "sverilog" => Seq(RunFirrtlTransformAnnotation(new SystemVerilogEmitter),
+ EmitAllModulesAnnotation(classOf[SystemVerilogEmitter]))
+ case _ => throw new PhaseException(s"Unknown emitter '$x'! (Did you misspell it?)")
+ }
+ xx ++ c }
+ .text("Run the specified module emitter (one file per module)")
+}
+
// ***** Annotations for results of emission *****
sealed abstract class EmittedComponent {
def name: String
def value: String
+ def outputSuffix: String
}
sealed abstract class EmittedCircuit extends EmittedComponent
-final case class EmittedFirrtlCircuit(name: String, value: String) extends EmittedCircuit
-final case class EmittedVerilogCircuit(name: String, value: String) extends EmittedCircuit
+final case class EmittedFirrtlCircuit(name: String, value: String, outputSuffix: String) extends EmittedCircuit
+final case class EmittedVerilogCircuit(name: String, value: String, outputSuffix: String) extends EmittedCircuit
sealed abstract class EmittedModule extends EmittedComponent
-final case class EmittedFirrtlModule(name: String, value: String) extends EmittedModule
-final case class EmittedVerilogModule(name: String, value: String) extends EmittedModule
+final case class EmittedFirrtlModule(name: String, value: String, outputSuffix: String) extends EmittedModule
+final case class EmittedVerilogModule(name: String, value: String, outputSuffix: String) extends EmittedModule
/** Traits for Annotations containing emitted components */
sealed trait EmittedAnnotation[T <: EmittedComponent] extends NoTargetAnnotation {
@@ -51,19 +107,21 @@ sealed trait EmittedCircuitAnnotation[T <: EmittedCircuit] extends EmittedAnnota
sealed trait EmittedModuleAnnotation[T <: EmittedModule] extends EmittedAnnotation[T]
case class EmittedFirrtlCircuitAnnotation(value: EmittedFirrtlCircuit)
- extends EmittedCircuitAnnotation[EmittedFirrtlCircuit]
+ extends EmittedCircuitAnnotation[EmittedFirrtlCircuit]
case class EmittedVerilogCircuitAnnotation(value: EmittedVerilogCircuit)
- extends EmittedCircuitAnnotation[EmittedVerilogCircuit]
+ extends EmittedCircuitAnnotation[EmittedVerilogCircuit]
case class EmittedFirrtlModuleAnnotation(value: EmittedFirrtlModule)
- extends EmittedModuleAnnotation[EmittedFirrtlModule]
+ extends EmittedModuleAnnotation[EmittedFirrtlModule]
case class EmittedVerilogModuleAnnotation(value: EmittedVerilogModule)
- extends EmittedModuleAnnotation[EmittedVerilogModule]
+ extends EmittedModuleAnnotation[EmittedVerilogModule]
sealed abstract class FirrtlEmitter(form: CircuitForm) extends Transform with Emitter {
def inputForm = form
def outputForm = form
+ val outputSuffix: String = form.outputSuffix
+
private def emitAllModules(circuit: Circuit): Seq[EmittedFirrtlModule] = {
// For a given module, returns a Seq of all modules instantited inside of it
def collectInstantiatedModules(mod: Module, map: Map[String, DefModule]): Seq[DefModule] = {
@@ -87,15 +145,15 @@ sealed abstract class FirrtlEmitter(form: CircuitForm) extends Transform with Em
case ext: ExtModule => ext
}
val newCircuit = Circuit(m.info, extModules :+ m, m.name)
- EmittedFirrtlModule(m.name, newCircuit.serialize)
+ EmittedFirrtlModule(m.name, newCircuit.serialize, outputSuffix)
}
}
override def execute(state: CircuitState): CircuitState = {
val newAnnos = state.annotations.flatMap {
case EmitCircuitAnnotation(_) =>
- Seq(EmittedFirrtlCircuitAnnotation.apply(
- EmittedFirrtlCircuit(state.circuit.main, state.circuit.serialize)))
+ Seq(EmittedFirrtlCircuitAnnotation(
+ EmittedFirrtlCircuit(state.circuit.main, state.circuit.serialize, outputSuffix)))
case EmitAllModulesAnnotation(_) =>
emitAllModules(state.circuit) map (EmittedFirrtlModuleAnnotation(_))
case _ => Seq()
@@ -129,6 +187,7 @@ case class VRandom(width: BigInt) extends Expression {
class VerilogEmitter extends SeqTransform with Emitter {
def inputForm = LowForm
def outputForm = LowForm
+ val outputSuffix = ".v"
val tab = " "
def AND(e1: WrappedExpression, e2: WrappedExpression): Expression = {
if (e1 == e2) e1.e1
@@ -363,8 +422,8 @@ class VerilogEmitter extends SeqTransform with Emitter {
* @return the render reference
*/
def getRenderer(descriptions: Seq[DescriptionAnnotation],
- m: Module,
- moduleMap: Map[String, DefModule])(implicit writer: Writer): VerilogRender = {
+ m: Module,
+ moduleMap: Map[String, DefModule])(implicit writer: Writer): VerilogRender = {
val newMod = new AddDescriptionNodes().executeModule(m, descriptions)
newMod match {
@@ -384,9 +443,9 @@ class VerilogEmitter extends SeqTransform with Emitter {
* @param writer where rendered information is placed.
*/
class VerilogRender(description: Description,
- portDescriptions: Map[String, Description],
- m: Module,
- moduleMap: Map[String, DefModule])(implicit writer: Writer) {
+ portDescriptions: Map[String, Description],
+ m: Module,
+ moduleMap: Map[String, DefModule])(implicit writer: Writer) {
def this(m: Module, moduleMap: Map[String, DefModule])(implicit writer: Writer) {
this(EmptyDescription, Map.empty, m, moduleMap)(writer)
@@ -458,7 +517,7 @@ class VerilogEmitter extends SeqTransform with Emitter {
assigns += Seq("assign ", e, " = ", syn, ";", info)
assigns += Seq("`else")
assigns += Seq("assign ", e, " = ", garbageCond, " ? ", rand_string(syn.tpe), " : ", syn,
- ";", info)
+ ";", info)
assigns += Seq("`endif // RANDOMIZE_GARBAGE_ASSIGN")
}
@@ -550,7 +609,7 @@ class VerilogEmitter extends SeqTransform with Emitter {
initials += Seq("`ifdef RANDOMIZE_MEM_INIT")
initials += Seq("for (initvar = 0; initvar < ", bigIntToVLit(s.depth), "; initvar = initvar+1)")
initials += Seq(tab, WSubAccess(wref(s.name, s.dataType), index, s.dataType, FEMALE),
- " = ", rstring, ";")
+ " = ", rstring, ";")
initials += Seq("`endif // RANDOMIZE_MEM_INIT")
}
@@ -696,14 +755,14 @@ class VerilogEmitter extends SeqTransform with Emitter {
instdeclares += Seq(");")
case sx: DefMemory =>
val fullSize = sx.depth * (sx.dataType match {
- case GroundType(IntWidth(width)) => width
- })
+ case GroundType(IntWidth(width)) => width
+ })
val decl = if (fullSize > (1 << 29)) "reg /* sparse */" else "reg"
declareVectorType(decl, sx.name, sx.dataType, sx.depth, sx.info)
initialize_mem(sx)
if (sx.readLatency != 0 || sx.writeLatency != 1)
throw EmitterException("All memories should be transformed into " +
- "blackboxes or combinational by previous passses")
+ "blackboxes or combinational by previous passses")
for (r <- sx.readers) {
val data = memPortField(sx, r, "data")
val addr = memPortField(sx, r, "addr")
@@ -717,7 +776,7 @@ class VerilogEmitter extends SeqTransform with Emitter {
//; Read port
assign(addr, netlist(addr), NoInfo) // Info should come from addr connection
- // assign(en, netlist(en)) //;Connects value to m.r.en
+ // assign(en, netlist(en)) //;Connects value to m.r.en
val mem = WRef(sx.name, memType(sx), MemKind, UNKNOWNGENDER)
val memPort = WSubAccess(mem, addr, sx.dataType, UNKNOWNGENDER)
val depthValue = UIntLiteral(sx.depth, IntWidth(sx.depth.bitLength))
@@ -756,7 +815,7 @@ class VerilogEmitter extends SeqTransform with Emitter {
if (sx.readwriters.nonEmpty)
throw EmitterException("All readwrite ports should be transformed into " +
- "read & write ports by previous passes")
+ "read & write ports by previous passes")
case _ =>
}
}
@@ -918,7 +977,7 @@ class VerilogEmitter extends SeqTransform with Emitter {
case EmitCircuitAnnotation(_) =>
val writer = new java.io.StringWriter
emit(state, writer)
- Seq(EmittedVerilogCircuitAnnotation(EmittedVerilogCircuit(state.circuit.main, writer.toString)))
+ Seq(EmittedVerilogCircuitAnnotation(EmittedVerilogCircuit(state.circuit.main, writer.toString, outputSuffix)))
case EmitAllModulesAnnotation(_) =>
val circuit = runTransforms(state).circuit
@@ -929,12 +988,12 @@ class VerilogEmitter extends SeqTransform with Emitter {
val writer = new java.io.StringWriter
val renderer = new VerilogRender(d, pds, module, moduleMap)(writer)
renderer.emit_verilog()
- Some(EmittedVerilogModuleAnnotation(EmittedVerilogModule(module.name, writer.toString)))
+ Some(EmittedVerilogModuleAnnotation(EmittedVerilogModule(module.name, writer.toString, outputSuffix)))
case module: Module =>
val writer = new java.io.StringWriter
val renderer = new VerilogRender(module, moduleMap)(writer)
renderer.emit_verilog()
- Some(EmittedVerilogModuleAnnotation(EmittedVerilogModule(module.name, writer.toString)))
+ Some(EmittedVerilogModuleAnnotation(EmittedVerilogModule(module.name, writer.toString, outputSuffix)))
case _ => None
}
case _ => Seq()
@@ -952,3 +1011,9 @@ class MinimumVerilogEmitter extends VerilogEmitter with Emitter {
}
}
+
+class SystemVerilogEmitter extends VerilogEmitter {
+ StageUtils.dramaticWarning("SystemVerilog Emitter is the same as the Verilog Emitter!")
+
+ override val outputSuffix: String = ".sv"
+}