aboutsummaryrefslogtreecommitdiff
path: root/src/main/scala/firrtl/Driver.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/Driver.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/Driver.scala')
-rw-r--r--src/main/scala/firrtl/Driver.scala130
1 files changed, 33 insertions, 97 deletions
diff --git a/src/main/scala/firrtl/Driver.scala b/src/main/scala/firrtl/Driver.scala
index e96c3c5b..f23be6f5 100644
--- a/src/main/scala/firrtl/Driver.scala
+++ b/src/main/scala/firrtl/Driver.scala
@@ -4,11 +4,10 @@ package firrtl
import scala.collection._
import scala.io.Source
-import scala.sys.process.{BasicIO, ProcessLogger, stringSeqToProcess}
import scala.util.{Failure, Success, Try}
import scala.util.control.ControlThrowable
import java.io.{File, FileNotFoundException}
-
+import scala.sys.process.{BasicIO, ProcessLogger, stringSeqToProcess}
import net.jcazevedo.moultingyaml._
import logger.Logger
import Parser.{IgnoreInfo, InfoMode}
@@ -17,6 +16,10 @@ import firrtl.annotations.AnnotationYamlProtocol._
import firrtl.passes.{PassException, PassExceptions}
import firrtl.transforms._
import firrtl.Utils.throwInternalError
+import firrtl.stage.{FirrtlExecutionResultView, FirrtlStage}
+import firrtl.stage.phases.DriverCompatibility
+import firrtl.options.{StageUtils, Phase}
+import firrtl.options.Viewer.view
/**
@@ -40,30 +43,22 @@ import firrtl.Utils.throwInternalError
* @see firrtlTests/DriverSpec.scala in the test directory for a lot more examples
* @see [[CompilerUtils.mergeTransforms]] to see how customTransformations are inserted
*/
-
+@deprecated("Use firrtl.stage.FirrtlStage", "1.2")
object Driver {
/** Print a warning message
*
* @param message error message
*/
- //scalastyle:off regex
- def dramaticWarning(message: String): Unit = {
- println(Console.YELLOW + "-"*78)
- println(s"Warning: $message")
- println("-"*78 + Console.RESET)
- }
+ @deprecated("Use firrtl.options.StageUtils.dramaticWarning", "1.2")
+ def dramaticWarning(message: String): Unit = StageUtils.dramaticWarning(message)
/**
* print the message in red
*
* @param message error message
*/
- //scalastyle:off regex
- def dramaticError(message: String): Unit = {
- println(Console.RED + "-"*78)
- println(s"Error: $message")
- println("-"*78 + Console.RESET)
- }
+ @deprecated("Use firrtl.options.StageUtils.dramaticWarning", "1.2")
+ def dramaticError(message: String): Unit = StageUtils.dramaticError(message)
/** Load annotation file based on options
* @param optionsManager use optionsManager config to load annotation file if it exists
@@ -107,7 +102,7 @@ object Driver {
if (firrtlConfig.annotationFileNameOverride.nonEmpty) {
val msg = "annotationFileNameOverride is deprecated! " +
"Use annotationFileNames"
- Driver.dramaticWarning(msg)
+ dramaticWarning(msg)
} else if (usingImplicitAnnoFile) {
val msg = "Implicit .anno file from top-name is deprecated!\n" +
(" "*9) + "Use explicit -faf option or annotationFileNames"
@@ -159,7 +154,7 @@ object Driver {
}
// Useful for handling erros in the options
- case class OptionsException(msg: String) extends Exception(msg)
+ case class OptionsException(message: String) extends Exception(message)
/** Get the Circuit from the compile options
*
@@ -216,77 +211,25 @@ object Driver {
* @return a FirrtlExecutionResult indicating success or failure, provide access to emitted data on success
* for downstream tools as desired
*/
- //scalastyle:off cyclomatic.complexity method.length
def execute(optionsManager: ExecutionOptionsManager with HasFirrtlOptions): FirrtlExecutionResult = {
- def firrtlConfig = optionsManager.firrtlOptions
-
- Logger.makeScope(optionsManager) {
- // Wrap compilation in a try/catch to present Scala MatchErrors in a more user-friendly format.
- val finalState = try {
- val circuit = getCircuit(optionsManager) match {
- case Success(c) => c
- case Failure(OptionsException(msg)) =>
- dramaticError(msg)
- return FirrtlExecutionFailure(msg)
- case Failure(e) => throw e
- }
+ StageUtils.dramaticWarning("firrtl.Driver is deprecated since 1.2!\nPlease switch to firrtl.stage.FirrtlStage")
- val annos = getAnnotations(optionsManager)
+ val annos = optionsManager.firrtlOptions.toAnnotations ++ optionsManager.commonOptions.toAnnotations
- // Does this need to be before calling compiler?
- optionsManager.makeTargetDir()
+ val phases: Seq[Phase] = Seq(
+ new DriverCompatibility.AddImplicitAnnotationFile,
+ new DriverCompatibility.AddImplicitFirrtlFile,
+ new DriverCompatibility.AddImplicitOutputFile,
+ new DriverCompatibility.AddImplicitEmitter,
+ new FirrtlStage )
- firrtlConfig.compiler.compile(
- CircuitState(circuit, ChirrtlForm, annos),
- firrtlConfig.customTransforms
- )
- }
- catch {
- // Rethrow the exceptions which are expected or due to the runtime environment (out of memory, stack overflow)
- case p: ControlThrowable => throw p
- case p: PassException => throw p
- case p: PassExceptions => throw p
- case p: FIRRTLException => throw p
- // Propagate exceptions from custom transforms
- case CustomTransformException(cause) => throw cause
- // Treat remaining exceptions as internal errors.
- case e: Exception => throwInternalError(exception = Some(e))
- }
-
- // Do emission
- // Note: Single emission target assumption is baked in here
- // Note: FirrtlExecutionSuccess emitted is only used if we're emitting the whole Circuit
- val emittedRes = firrtlConfig.getOutputConfig(optionsManager) match {
- case SingleFile(filename) =>
- val emitted = finalState.getEmittedCircuit
- val outputFile = new java.io.PrintWriter(filename)
- outputFile.write(emitted.value)
- outputFile.close()
- emitted.value
- case OneFilePerModule(dirName) =>
- val emittedModules = finalState.emittedComponents collect { case x: EmittedModule => x }
- if (emittedModules.isEmpty) throwInternalError() // There should be something
- emittedModules.foreach { module =>
- val filename = optionsManager.getBuildFileName(firrtlConfig.outputSuffix, s"$dirName/${module.name}")
- val outputFile = new java.io.PrintWriter(filename)
- outputFile.write(module.value)
- outputFile.close()
- }
- "" // Should we return something different here?
- }
-
- // If set, emit final annotations to a file
- optionsManager.firrtlOptions.outputAnnotationFileName match {
- case "" =>
- case file =>
- val filename = optionsManager.getBuildFileName("anno.json", file)
- val outputFile = new java.io.PrintWriter(filename)
- outputFile.write(JsonProtocol.serialize(finalState.annotations))
- outputFile.close()
- }
-
- FirrtlExecutionSuccess(firrtlConfig.compilerName, emittedRes, finalState)
+ val annosx = try {
+ phases.foldLeft(annos)( (a, p) => p.runTransform(a) )
+ } catch {
+ case e: firrtl.options.OptionsException => return FirrtlExecutionFailure(e.message)
}
+
+ view[FirrtlExecutionResult](annosx)
}
/**
@@ -321,23 +264,16 @@ object Driver {
}
object FileUtils {
- /**
- * recursive create directory and all parents
- *
+
+ /** Create a directory if it doesn't exist
* @param directoryName a directory string with one or more levels
- * @return
+ * @return true if the directory exists or if it was successfully created
*/
def makeDirectory(directoryName: String): Boolean = {
- val dirFile = new java.io.File(directoryName)
+ val dirFile = new File(directoryName)
if(dirFile.exists()) {
- if(dirFile.isDirectory) {
- true
- }
- else {
- false
- }
- }
- else {
+ dirFile.isDirectory
+ } else {
dirFile.mkdirs()
}
}
@@ -361,7 +297,7 @@ object FileUtils {
if(file.getPath.split("/").last.isEmpty ||
file.getAbsolutePath == "/" ||
file.getPath.startsWith("/")) {
- Driver.dramaticError(s"delete directory ${file.getPath} will not delete absolute paths")
+ StageUtils.dramaticError(s"delete directory ${file.getPath} will not delete absolute paths")
false
}
else {