From 2a96767097264eade18ff26e1d8bce192383a190 Mon Sep 17 00:00:00 2001 From: SoyaOhnishi Date: Mon, 25 Jan 2021 11:15:52 +0900 Subject: Refactor EnumAnnotations and EnumFactory (#1747) This is a nit fix. no logic is changed. * Rename `typeName` to `enumTypeName` in ScalaDoc * Add return type at public method * Rename `enum_records` into `enumRecords` to retain name consistency Co-authored-by: Jack Koenig --- core/src/main/scala/chisel3/StrongEnum.scala | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) (limited to 'core/src') diff --git a/core/src/main/scala/chisel3/StrongEnum.scala b/core/src/main/scala/chisel3/StrongEnum.scala index 2d372a94..7d328eb7 100644 --- a/core/src/main/scala/chisel3/StrongEnum.scala +++ b/core/src/main/scala/chisel3/StrongEnum.scala @@ -18,7 +18,7 @@ object EnumAnnotations { /** An annotation for strong enum instances that are ''not'' inside of Vecs * * @param target the enum instance being annotated - * @param typeName the name of the enum's type (e.g. ''"mypackage.MyEnum"'') + * @param enumTypeName the name of the enum's type (e.g. ''"mypackage.MyEnum"'') */ case class EnumComponentAnnotation(target: Named, enumTypeName: String) extends SingleTargetAnnotation[Named] { def duplicate(n: Named): EnumComponentAnnotation = this.copy(target = n) @@ -50,11 +50,11 @@ object EnumAnnotations { * */ case class EnumVecAnnotation(target: Named, typeName: String, fields: Seq[Seq[String]]) extends SingleTargetAnnotation[Named] { - def duplicate(n: Named) = this.copy(target = n) + def duplicate(n: Named): EnumVecAnnotation = this.copy(target = n) } case class EnumVecChiselAnnotation(target: InstanceId, typeName: String, fields: Seq[Seq[String]]) extends ChiselAnnotation { - override def toFirrtl = EnumVecAnnotation(target.toNamed, typeName, fields) + override def toFirrtl: EnumVecAnnotation = EnumVecAnnotation(target.toNamed, typeName, fields) } /** An annotation for enum types (rather than enum ''instances''). @@ -225,11 +225,11 @@ abstract class EnumFactory { private[chisel3] var width: Width = 0.W private case class EnumRecord(inst: Type, name: String) - private val enum_records = mutable.ArrayBuffer.empty[EnumRecord] + private val enumRecords = mutable.ArrayBuffer.empty[EnumRecord] - private def enumNames = enum_records.map(_.name).toSeq - private def enumValues = enum_records.map(_.inst.litValue()).toSeq - private def enumInstances = enum_records.map(_.inst).toSeq + private def enumNames = enumRecords.map(_.name).toSeq + private def enumValues = enumRecords.map(_.inst.litValue()).toSeq + private def enumInstances = enumRecords.map(_.inst).toSeq private[chisel3] val enumTypeName = getClass.getName.init @@ -241,7 +241,7 @@ abstract class EnumFactory { def all: Seq[Type] = enumInstances private[chisel3] def nameOfValue(id: BigInt): Option[String] = { - enum_records.find(_.inst.litValue() == id).map(_.name) + enumRecords.find(_.inst.litValue() == id).map(_.name) } protected def Value: Type = macro EnumMacros.ValImpl @@ -253,7 +253,7 @@ abstract class EnumFactory { // We have to use UnknownWidth here, because we don't actually know what the final width will be result.bindToLiteral(id, UnknownWidth()) - enum_records.append(EnumRecord(result, name)) + enumRecords.append(EnumRecord(result, name)) width = (1 max id.bitLength).W id += 1 -- cgit v1.2.3 From d0db0b8b4661e64a79e8b14a24a4fa1baace1c3d Mon Sep 17 00:00:00 2001 From: Jack Koenig Date: Tue, 26 Jan 2021 17:15:57 -0800 Subject: Fix incorrect comment in ScalaDoc (#1756) --- core/src/main/scala/chisel3/Reg.scala | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'core/src') diff --git a/core/src/main/scala/chisel3/Reg.scala b/core/src/main/scala/chisel3/Reg.scala index b2b99cc1..bd9e5311 100644 --- a/core/src/main/scala/chisel3/Reg.scala +++ b/core/src/main/scala/chisel3/Reg.scala @@ -127,7 +127,7 @@ object RegNext { * val x = Wire(UInt()) * val y = Wire(UInt(8.W)) * val r1 = RegInit(x) // width will be inferred - * val r2 = RegInit(y) // width is set to 8 + * val r2 = RegInit(y) // width will be inferred * }}} * * 3. [[Aggregate]] initializer - width will be set to match the aggregate -- cgit v1.2.3 From 98ce9194e5d87fdd5be931b6cd516d180a6540cd Mon Sep 17 00:00:00 2001 From: Albert Magyar Date: Mon, 1 Feb 2021 14:06:39 -0800 Subject: Update reported width from div/rem to match FIRRTL results (#1748) * Update reported width from div/rem to match FIRRTL results * Add tests for width of % and / on UInt and SInt * Add loop-based test for known UInt/SInt op result widths Co-authored-by: Jack Koenig --- core/src/main/scala/chisel3/Bits.scala | 6 +++--- core/src/main/scala/chisel3/internal/firrtl/IR.scala | 1 + 2 files changed, 4 insertions(+), 3 deletions(-) (limited to 'core/src') diff --git a/core/src/main/scala/chisel3/Bits.scala b/core/src/main/scala/chisel3/Bits.scala index 6bd5a07c..c86e9208 100644 --- a/core/src/main/scala/chisel3/Bits.scala +++ b/core/src/main/scala/chisel3/Bits.scala @@ -448,7 +448,7 @@ sealed class UInt private[chisel3] (width: Width) extends Bits(width) with Num[U override def do_/ (that: UInt)(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): UInt = binop(sourceInfo, UInt(this.width), DivideOp, that) override def do_% (that: UInt)(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): UInt = - binop(sourceInfo, UInt(this.width), RemOp, that) + binop(sourceInfo, UInt(this.width min that.width), RemOp, that) override def do_* (that: UInt)(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): UInt = binop(sourceInfo, UInt(this.width + that.width), TimesOp, that) @@ -762,9 +762,9 @@ sealed class SInt private[chisel3] (width: Width) extends Bits(width) with Num[S override def do_* (that: SInt)(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): SInt = binop(sourceInfo, SInt(this.width + that.width), TimesOp, that) override def do_/ (that: SInt)(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): SInt = - binop(sourceInfo, SInt(this.width), DivideOp, that) + binop(sourceInfo, SInt(this.width + 1), DivideOp, that) override def do_% (that: SInt)(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): SInt = - binop(sourceInfo, SInt(this.width), RemOp, that) + binop(sourceInfo, SInt(this.width min that.width), RemOp, that) /** Multiplication operator * diff --git a/core/src/main/scala/chisel3/internal/firrtl/IR.scala b/core/src/main/scala/chisel3/internal/firrtl/IR.scala index 095c8a05..61f97ce6 100644 --- a/core/src/main/scala/chisel3/internal/firrtl/IR.scala +++ b/core/src/main/scala/chisel3/internal/firrtl/IR.scala @@ -158,6 +158,7 @@ object Width { sealed abstract class Width { type W = Int + def min(that: Width): Width = this.op(that, _ min _) def max(that: Width): Width = this.op(that, _ max _) def + (that: Width): Width = this.op(that, _ + _) def + (that: Int): Width = this.op(this, (a, b) => a + that) -- cgit v1.2.3 From f45216effc573d33d4aa4e525cff955ab332efbd Mon Sep 17 00:00:00 2001 From: Jiuyang Liu Date: Thu, 4 Feb 2021 00:36:12 +0000 Subject: Remove Deprecated APIs (#1730) --- core/src/main/scala/chisel3/Bits.scala | 26 -- core/src/main/scala/chisel3/Data.scala | 8 - core/src/main/scala/chisel3/core/package.scala | 288 --------------------- .../main/scala/chisel3/experimental/package.scala | 7 - core/src/main/scala/chisel3/internal/Error.scala | 7 - 5 files changed, 336 deletions(-) delete mode 100644 core/src/main/scala/chisel3/core/package.scala (limited to 'core/src') diff --git a/core/src/main/scala/chisel3/Bits.scala b/core/src/main/scala/chisel3/Bits.scala index c86e9208..17829143 100644 --- a/core/src/main/scala/chisel3/Bits.scala +++ b/core/src/main/scala/chisel3/Bits.scala @@ -29,15 +29,6 @@ private[chisel3] sealed trait ToBoolable extends Element { /** @group SourceInfoTransformMacro */ def do_asBool(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Bool - - /** Casts this $coll to a [[Bool]] - * - * @note The width must be known and equal to 1 - */ - final def toBool(): Bool = macro SourceInfoWhiteboxTransform.noArg - - /** @group SourceInfoTransformMacro */ - def do_toBool(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Bool } /** A data type for values represented by a single bitvector. This provides basic bitwise operations. @@ -315,11 +306,6 @@ sealed abstract class Bits(private[chisel3] val width: Width) extends Element wi /** Returns the contents of this wire as a [[scala.collection.Seq]] of [[Bool]]. */ final def toBools(): Seq[Bool] = macro SourceInfoTransform.noArg - /** @group SourceInfoTransformMacro */ - @chiselRuntimeDeprecated - @deprecated("Use asBools instead", "3.2") - def do_toBools(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Seq[Bool] = do_asBools - /** Returns the contents of this wire as a [[scala.collection.Seq]] of [[Bool]]. */ final def asBools(): Seq[Bool] = macro SourceInfoTransform.noArg @@ -369,10 +355,6 @@ sealed abstract class Bits(private[chisel3] val width: Width) extends Element wi } } - @chiselRuntimeDeprecated - @deprecated("Use asBool instead", "3.2") - final def do_toBool(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Bool = do_asBool - /** Concatenation operator * * @param that a hardware component @@ -591,10 +573,6 @@ sealed class UInt private[chisel3] (width: Width) extends Bits(width) with Num[U override def do_<= (that: UInt)(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Bool = compop(sourceInfo, LessEqOp, that) override def do_>= (that: UInt)(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Bool = compop(sourceInfo, GreaterEqOp, that) - @chiselRuntimeDeprecated - @deprecated("Use '=/=', which avoids potential precedence problems", "3.0") - final def != (that: UInt)(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Bool = this =/= that - /** Dynamic not equals operator * * @param that a hardware $coll @@ -877,10 +855,6 @@ sealed class SInt private[chisel3] (width: Width) extends Bits(width) with Num[S override def do_<= (that: SInt)(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Bool = compop(sourceInfo, LessEqOp, that) override def do_>= (that: SInt)(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Bool = compop(sourceInfo, GreaterEqOp, that) - @chiselRuntimeDeprecated - @deprecated("Use '=/=', which avoids potential precedence problems", "3.0") - final def != (that: SInt)(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Bool = this =/= that - /** Dynamic not equals operator * * @param that a hardware $coll diff --git a/core/src/main/scala/chisel3/Data.scala b/core/src/main/scala/chisel3/Data.scala index a1f6abf8..332527bf 100644 --- a/core/src/main/scala/chisel3/Data.scala +++ b/core/src/main/scala/chisel3/Data.scala @@ -554,14 +554,6 @@ abstract class Data extends HasId with NamedComponent with SourceInfoDoc { } } - @chiselRuntimeDeprecated - @deprecated("litArg is deprecated, use litOption or litTo*Option", "3.2") - def litArg(): Option[LitArg] = topBindingOpt match { - case Some(ElementLitBinding(litArg)) => Some(litArg) - case Some(BundleLitBinding(litMap)) => None // this API does not support Bundle literals - case _ => None - } - def isLit(): Boolean = litOption.isDefined /** diff --git a/core/src/main/scala/chisel3/core/package.scala b/core/src/main/scala/chisel3/core/package.scala deleted file mode 100644 index fa29f244..00000000 --- a/core/src/main/scala/chisel3/core/package.scala +++ /dev/null @@ -1,288 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 - -package chisel3 - -/** - * These definitions exist to deal with those clients that relied on chisel3.core. - * They are deprecated and will be removed in the future. - */ -package object core { - - @deprecated("Use the version in chisel3._", "3.2") - val CompileOptions = chisel3.CompileOptions - - @deprecated("Use the version in chisel3._", "3.2") - val Input = chisel3.Input - @deprecated("Use the version in chisel3._", "3.2") - val Output = chisel3.Output - @deprecated("Use the version in chisel3._", "3.2") - val Flipped = chisel3.Flipped - @deprecated("Use the version in chisel3._", "3.2") - val chiselTypeOf = chisel3.chiselTypeOf - - @deprecated("Use the version in chisel3._", "3.2") - type Data = chisel3.Data - - @deprecated("Use the version in chisel3._", "3.2") - val WireDefault = chisel3.WireDefault - - @deprecated("Use the version in chisel3._", "3.2") - val Clock = chisel3.Clock - @deprecated("Use the version in chisel3._", "3.2") - type Clock = chisel3.Clock - - @deprecated("Use the version in chisel3._", "3.2") - type Reset = chisel3.Reset - - @deprecated("Use the version in chisel3._", "3.2") - type Aggregate = chisel3.Aggregate - - @deprecated("Use the version in chisel3._", "3.2") - val Vec = chisel3.Vec - @deprecated("Use the version in chisel3._", "3.2") - val VecInit = chisel3.VecInit - @deprecated("Use the version in chisel3._", "3.2") - type Vec[T <: Data] = chisel3.Vec[T] - @deprecated("Use the version in chisel3._", "3.2") - type VecLike[T <: Data] = chisel3.VecLike[T] - @deprecated("Use the version in chisel3._", "3.2") - type Bundle = chisel3.Bundle - @deprecated("Use the version in chisel3._", "3.2") - type IgnoreSeqInBundle = chisel3.IgnoreSeqInBundle - @deprecated("Use the version in chisel3._", "3.2") - type Record = chisel3.Record - - @deprecated("Use the version in chisel3._", "3.2") - val assert = chisel3.assert - - @deprecated("Use the version in chisel3._", "3.2") - type Element = chisel3.Element - @deprecated("Use the version in chisel3._", "3.2") - type Bits = chisel3.Bits - - // These provide temporary compatibility for those who foolishly imported from chisel3.core - @deprecated("Avoid importing from chisel3.core, these are not public APIs and may change at any time. " + - " Use chisel3.RawModule instead. This alias will be removed in 3.4.", "since the beginning of time") - type RawModule = chisel3.RawModule - @deprecated("Avoid importing from chisel3.core, these are not public APIs and may change at any time. " + - "Use chisel3.MultiIOModule instead. This alias will be removed in 3.4.", "since the beginning of time") - type MultiIOModule = chisel3.Module - @deprecated("Avoid importing from chisel3.core, these are not public APIs and may change at any time. " + - " Use chisel3.RawModule instead. This alias will be removed in 3.4.", "since the beginning of time") - type UserModule = chisel3.RawModule - @deprecated("Avoid importing from chisel3.core, these are not public APIs and may change at any time. " + - "Use chisel3.MultiIOModule instead. This alias will be removed in 3.4.", "since the beginning of time") - type ImplicitModule = chisel3.Module - - @deprecated("Use the version in chisel3._", "3.2") - val Bits = chisel3.Bits - @deprecated("Use the version in chisel3._", "3.2") - type Num[T <: chisel3.Data] = chisel3.Num[T] - @deprecated("Use the version in chisel3._", "3.2") - type UInt = chisel3.UInt - @deprecated("Use the version in chisel3._", "3.2") - val UInt = chisel3.UInt - @deprecated("Use the version in chisel3._", "3.2") - type SInt = chisel3.SInt - @deprecated("Use the version in chisel3._", "3.2") - val SInt = chisel3.SInt - @deprecated("Use the version in chisel3._", "3.2") - type Bool = chisel3.Bool - @deprecated("Use the version in chisel3._", "3.2") - val Bool = chisel3.Bool - @deprecated("Use the version in chisel3._", "3.2") - val Mux = chisel3.Mux - - @deprecated("Use the version in chisel3._", "3.2") - type BlackBox = chisel3.BlackBox - - @deprecated("Use the version in chisel3._", "3.2") - val Mem = chisel3.Mem - @deprecated("Use the version in chisel3._", "3.2") - type MemBase[T <: chisel3.Data] = chisel3.MemBase[T] - @deprecated("Use the version in chisel3._", "3.2") - type Mem[T <: chisel3.Data] = chisel3.Mem[T] - @deprecated("Use the version in chisel3._", "3.2") - val SyncReadMem = chisel3.SyncReadMem - @deprecated("Use the version in chisel3._", "3.2") - type SyncReadMem[T <: chisel3.Data] = chisel3.SyncReadMem[T] - - @deprecated("Use the version in chisel3._", "3.2") - val Module = chisel3.Module - @deprecated("Use the version in chisel3._", "3.2") - type Module = chisel3.Module - - @deprecated("Use the version in chisel3._", "3.2") - val printf = chisel3.printf - - @deprecated("Use the version in chisel3._", "3.2") - val RegNext = chisel3.RegNext - @deprecated("Use the version in chisel3._", "3.2") - val RegInit = chisel3.RegInit - @deprecated("Use the version in chisel3._", "3.2") - val Reg = chisel3.Reg - - @deprecated("Use the version in chisel3._", "3.2") - val when = chisel3.when - @deprecated("Use the version in chisel3._", "3.2") - type WhenContext = chisel3.WhenContext - - @deprecated("Use the version in chisel3._", "3.2") - type Printable = chisel3.Printable - @deprecated("Use the version in chisel3._", "3.2") - val Printable = chisel3.Printable - @deprecated("Use the version in chisel3._", "3.2") - type Printables = chisel3.Printables - @deprecated("Use the version in chisel3._", "3.2") - val Printables = chisel3.Printables - @deprecated("Use the version in chisel3._", "3.2") - type PString = chisel3.PString - @deprecated("Use the version in chisel3._", "3.2") - val PString = chisel3.PString - @deprecated("Use the version in chisel3._", "3.2") - type FirrtlFormat = chisel3.FirrtlFormat - @deprecated("Use the version in chisel3._", "3.2") - val FirrtlFormat = chisel3.FirrtlFormat - @deprecated("Use the version in chisel3._", "3.2") - type Decimal = chisel3.Decimal - @deprecated("Use the version in chisel3._", "3.2") - val Decimal = chisel3.Decimal - @deprecated("Use the version in chisel3._", "3.2") - type Hexadecimal = chisel3.Hexadecimal - val Hexadecimal = chisel3.Hexadecimal - @deprecated("Use the version in chisel3._", "3.2") - type Binary = chisel3.Binary - @deprecated("Use the version in chisel3._", "3.2") - val Binary = chisel3.Binary - @deprecated("Use the version in chisel3._", "3.2") - type Character = chisel3.Character - @deprecated("Use the version in chisel3._", "3.2") - val Character = chisel3.Character - @deprecated("Use the version in chisel3._", "3.2") - type Name = chisel3.Name - @deprecated("Use the version in chisel3._", "3.2") - val Name = chisel3.Name - @deprecated("Use the version in chisel3._", "3.2") - type FullName = chisel3.FullName - @deprecated("Use the version in chisel3._", "3.2") - val FullName = chisel3.FullName - @deprecated("Use the version in chisel3._", "3.2") - val Percent = chisel3.Percent - - @deprecated("Use the version in chisel3.experimental._", "3.2") - type Param = chisel3.experimental.Param - @deprecated("Use the version in chisel3.experimental._", "3.2") - type IntParam = chisel3.experimental.IntParam - @deprecated("Use the version in chisel3.experimental._", "3.2") - val IntParam = chisel3.experimental.IntParam - @deprecated("Use the version in chisel3.experimental._", "3.2") - type DoubleParam = chisel3.experimental.DoubleParam - @deprecated("Use the version in chisel3.experimental._", "3.2") - val DoubleParam = chisel3.experimental.DoubleParam - @deprecated("Use the version in chisel3.experimental._", "3.2") - type StringParam = chisel3.experimental.StringParam - @deprecated("Use the version in chisel3.experimental._", "3.2") - val StringParam = chisel3.experimental.StringParam - @deprecated("Use the version in chisel3.experimental._", "3.2") - type RawParam = chisel3.experimental.RawParam - @deprecated("Use the version in chisel3.experimental._", "3.2") - val RawParam = chisel3.experimental.RawParam - - @deprecated("Use the version in chisel3.experimental._", "3.2") - type Analog = chisel3.experimental.Analog - @deprecated("Use the version in chisel3.experimental._", "3.2") - val Analog = chisel3.experimental.Analog - - @deprecated("Use the version in chisel3._", "3.2") - implicit class fromIntToWidth(int: Int) extends chisel3.fromIntToWidth(int) - - @deprecated("Use the version in chisel3.experimental._", "3.2") - val attach = chisel3.experimental.attach - - @deprecated("Use the version in chisel3.experimental._", "3.2") - type EnumType = chisel3.experimental.EnumType - @deprecated("Use the version in chisel3.experimental._", "3.2") - type EnumFactory = chisel3.experimental.EnumFactory - @deprecated("Use the version in chisel3.experimental._", "3.2") - val EnumAnnotations = chisel3.experimental.EnumAnnotations - - @deprecated("Use the version in chisel3._", "3.2") - val withClockAndReset = chisel3.withClockAndReset - @deprecated("Use the version in chisel3._", "3.2") - val withClock = chisel3.withClock - @deprecated("Use the version in chisel3._", "3.2") - val withReset = chisel3.withReset - - @deprecated("Use the version in chisel3._", "3.2") - val dontTouch = chisel3.dontTouch - - @deprecated("Use the version in chisel3.experimental._", "3.2") - type BaseModule = chisel3.experimental.BaseModule - @deprecated("Use the version in chisel3.experimental._", "3.2") - type ExtModule = chisel3.experimental.ExtModule - - @deprecated("Use the version in chisel3.experimental._", "3.2") - val IO = chisel3.experimental.IO - - @deprecated("Use the version in chisel3.experimental._", "3.2") - type FixedPoint = chisel3.experimental.FixedPoint - @deprecated("Use the version in chisel3.experimental._", "3.2") - val FixedPoint = chisel3.experimental.FixedPoint - @deprecated("Use the version in chisel3.experimental._", "3.2") - implicit class fromDoubleToLiteral(double: Double) extends experimental.FixedPoint.Implicits.fromDoubleToLiteral(double) - @deprecated("Use the version in chisel3.experimental._", "3.2") - implicit class fromIntToBinaryPoint(int: Int) extends chisel3.fromIntToBinaryPoint(int) - @deprecated("Use the version in chisel3.experimental._", "3.2") - type RunFirrtlTransform = chisel3.experimental.RunFirrtlTransform - - @deprecated("Use the version in chisel3.experimental._", "3.2") - val annotate = chisel3.experimental.annotate - - @deprecated("Use the version in chisel3.experimental._", "3.2") - val DataMirror = chisel3.experimental.DataMirror - @deprecated("Use the version in chisel3._", "3.2") - type ActualDirection = chisel3.ActualDirection - @deprecated("Use the version in chisel3._", "3.2") - val ActualDirection = chisel3.ActualDirection - - @deprecated("Use the version in chisel3.internal._", "3.2") - val requireIsHardware = chisel3.internal.requireIsHardware - @deprecated("Use the version in chisel3.internal._", "3.2") - val requireIsChiselType = chisel3.internal.requireIsChiselType - @deprecated("Use the version in chisel3.internal._", "3.2") - val BiConnect = chisel3.internal.BiConnect - @deprecated("Use the version in chisel3.internal._", "3.2") - val MonoConnect = chisel3.internal.MonoConnect - @deprecated("Use the version in chisel3.internal._", "3.2") - val BindingDirection = chisel3.internal.BindingDirection - @deprecated("Use the version in chisel3.internal._", "3.2") - type Binding = chisel3.internal.Binding - @deprecated("Use the version in chisel3.internal._", "3.2") - type TopBinding = chisel3.internal.TopBinding - @deprecated("Use the version in chisel3.internal._", "3.2") - type UnconstrainedBinding = chisel3.internal.UnconstrainedBinding - @deprecated("Use the version in chisel3.internal._", "3.2") - type ConstrainedBinding = chisel3.internal.ConstrainedBinding - @deprecated("Use the version in chisel3.internal._", "3.2") - type ReadOnlyBinding = chisel3.internal.ReadOnlyBinding - @deprecated("Use the version in chisel3.internal._", "3.2") - type OpBinding = chisel3.internal.OpBinding - @deprecated("Use the version in chisel3.internal._", "3.2") - type MemoryPortBinding = chisel3.internal.MemoryPortBinding - @deprecated("Use the version in chisel3.internal._", "3.2") - type PortBinding = chisel3.internal.PortBinding - @deprecated("Use the version in chisel3.internal._", "3.2") - type RegBinding = chisel3.internal.RegBinding - @deprecated("Use the version in chisel3.internal._", "3.2") - type WireBinding = chisel3.internal.WireBinding - @deprecated("Use the version in chisel3.internal._", "3.2") - type ChildBinding = chisel3.internal.ChildBinding - @deprecated("Use the version in chisel3.internal._", "3.2") - type DontCareBinding = chisel3.internal.DontCareBinding - @deprecated("Use the version in chisel3.internal._", "3.2") - type LitBinding = chisel3.internal.LitBinding - @deprecated("Use the version in chisel3.internal._", "3.2") - type ElementLitBinding = chisel3.internal.ElementLitBinding - @deprecated("Use the version in chisel3.internal._", "3.2") - type BundleLitBinding = chisel3.internal.BundleLitBinding -} diff --git a/core/src/main/scala/chisel3/experimental/package.scala b/core/src/main/scala/chisel3/experimental/package.scala index ec3f2a79..4dc7ba4b 100644 --- a/core/src/main/scala/chisel3/experimental/package.scala +++ b/core/src/main/scala/chisel3/experimental/package.scala @@ -20,13 +20,6 @@ package object experimental { type ChiselEnum = EnumFactory - @deprecated("Use the version in chisel3._", "3.2") - val withClockAndReset = chisel3.withClockAndReset - @deprecated("Use the version in chisel3._", "3.2") - val withClock = chisel3.withClock - @deprecated("Use the version in chisel3._", "3.2") - val withReset = chisel3.withReset - // Rocket Chip-style clonemodule /** A record containing the results of CloneModuleAsRecord diff --git a/core/src/main/scala/chisel3/internal/Error.scala b/core/src/main/scala/chisel3/internal/Error.scala index 6a1794ce..60bb6e2b 100644 --- a/core/src/main/scala/chisel3/internal/Error.scala +++ b/core/src/main/scala/chisel3/internal/Error.scala @@ -61,13 +61,6 @@ class ChiselException(message: String, cause: Throwable = null) extends Exceptio trimmedReverse.reverse.toArray } - /** trims the top of the stack of elements belonging to [[blacklistPackages]] - * then trims the bottom elements until it reaches [[builderName]] - * then continues trimming elements belonging to [[blacklistPackages]] - */ - @deprecated("This method will be removed in 3.4", "3.3") - def trimmedStackTrace: Array[StackTraceElement] = trimmedStackTrace(this) - def chiselStackTrace: String = { val trimmed = trimmedStackTrace(likelyCause) -- cgit v1.2.3 From 0a0d7c6aac4326f2127d6d95efa5a4e10c81946c Mon Sep 17 00:00:00 2001 From: Jack Koenig Date: Mon, 12 Oct 2020 21:02:27 -0700 Subject: Make it possible to GC Data instances No longer create a pointer from parent to every HasId, only do it by default for BaseModules and MemBases. Add pointer from parent to Data upon binding the Data. * Add MemTypeBinding for port types of Mems This binding is similar to the SampleElementBinding for Vecs in that these Data are not truly hardware, but are represented in the FIRRTL IR and thus need some representation. * Call _onModuleClose on unbound Records This maintains some corner-case behavior that is nevertheless relied upon. It ensures that refs are set for the elements of Records, even if they are not bound to any real hardware. --- core/src/main/scala/chisel3/Aggregate.scala | 6 ++++-- core/src/main/scala/chisel3/BlackBox.scala | 2 ++ core/src/main/scala/chisel3/Data.scala | 5 +++-- core/src/main/scala/chisel3/Element.scala | 3 ++- core/src/main/scala/chisel3/Mem.scala | 4 ++++ core/src/main/scala/chisel3/Module.scala | 13 +++++++++++++ core/src/main/scala/chisel3/RawModule.scala | 2 ++ core/src/main/scala/chisel3/experimental/Analog.scala | 3 ++- core/src/main/scala/chisel3/internal/Binding.scala | 4 ++++ core/src/main/scala/chisel3/internal/Builder.scala | 1 - 10 files changed, 36 insertions(+), 7 deletions(-) (limited to 'core/src') diff --git a/core/src/main/scala/chisel3/Aggregate.scala b/core/src/main/scala/chisel3/Aggregate.scala index 403fcdba..f07b2543 100644 --- a/core/src/main/scala/chisel3/Aggregate.scala +++ b/core/src/main/scala/chisel3/Aggregate.scala @@ -20,7 +20,8 @@ class AliasedAggregateFieldException(message: String) extends ChiselException(me * of) other Data objects. */ sealed abstract class Aggregate extends Data { - private[chisel3] override def bind(target: Binding, parentDirection: SpecifiedDirection) { + private[chisel3] override def bind(target: Binding, parentDirection: SpecifiedDirection): Unit = { + _parent.foreach(_.addId(this)) binding = target val resolvedDirection = SpecifiedDirection.fromParent(parentDirection, specifiedDirection) @@ -166,7 +167,8 @@ sealed class Vec[T <: Data] private[chisel3] (gen: => T, val length: Int) case _ => false } - private[chisel3] override def bind(target: Binding, parentDirection: SpecifiedDirection) { + private[chisel3] override def bind(target: Binding, parentDirection: SpecifiedDirection): Unit = { + _parent.foreach(_.addId(this)) binding = target val resolvedDirection = SpecifiedDirection.fromParent(parentDirection, specifiedDirection) diff --git a/core/src/main/scala/chisel3/BlackBox.scala b/core/src/main/scala/chisel3/BlackBox.scala index 03543790..8ba4b612 100644 --- a/core/src/main/scala/chisel3/BlackBox.scala +++ b/core/src/main/scala/chisel3/BlackBox.scala @@ -81,6 +81,8 @@ package experimental { id._onModuleClose } + closeUnboundIds(names) + val firrtlPorts = getModulePorts map {port => Port(port, port.specifiedDirection)} val component = DefBlackBox(this, name, firrtlPorts, SpecifiedDirection.Unspecified, params) _component = Some(component) diff --git a/core/src/main/scala/chisel3/Data.scala b/core/src/main/scala/chisel3/Data.scala index 332527bf..377a94e6 100644 --- a/core/src/main/scala/chisel3/Data.scala +++ b/core/src/main/scala/chisel3/Data.scala @@ -339,13 +339,14 @@ abstract class Data extends HasId with NamedComponent with SourceInfoDoc { private[chisel3] final def isSynthesizable: Boolean = _binding.map { case ChildBinding(parent) => parent.isSynthesizable case _: TopBinding => true - case _: SampleElementBinding[_] => false + case (_: SampleElementBinding[_] | _: MemTypeBinding[_]) => false }.getOrElse(false) private[chisel3] def topBindingOpt: Option[TopBinding] = _binding.flatMap { case ChildBinding(parent) => parent.topBindingOpt case bindingVal: TopBinding => Some(bindingVal) case SampleElementBinding(parent) => parent.topBindingOpt + case _: MemTypeBinding[_] => None } private[chisel3] def topBinding: TopBinding = topBindingOpt.get @@ -355,7 +356,7 @@ abstract class Data extends HasId with NamedComponent with SourceInfoDoc { * node is the top-level. * binding and direction are valid after this call completes. */ - private[chisel3] def bind(target: Binding, parentDirection: SpecifiedDirection = SpecifiedDirection.Unspecified) + private[chisel3] def bind(target: Binding, parentDirection: SpecifiedDirection = SpecifiedDirection.Unspecified): Unit // Both _direction and _resolvedUserDirection are saved versions of computed variables (for // efficiency, avoid expensive recomputation of frequent operations). diff --git a/core/src/main/scala/chisel3/Element.scala b/core/src/main/scala/chisel3/Element.scala index 55415f3d..0c99ff70 100644 --- a/core/src/main/scala/chisel3/Element.scala +++ b/core/src/main/scala/chisel3/Element.scala @@ -17,7 +17,8 @@ abstract class Element extends Data { def widthKnown: Boolean = width.known def name: String = getRef.name - private[chisel3] override def bind(target: Binding, parentDirection: SpecifiedDirection) { + private[chisel3] override def bind(target: Binding, parentDirection: SpecifiedDirection): Unit = { + _parent.foreach(_.addId(this)) binding = target val resolvedDirection = SpecifiedDirection.fromParent(parentDirection, specifiedDirection) direction = ActualDirection.fromSpecified(resolvedDirection) diff --git a/core/src/main/scala/chisel3/Mem.scala b/core/src/main/scala/chisel3/Mem.scala index a60b31ac..90525bfa 100644 --- a/core/src/main/scala/chisel3/Mem.scala +++ b/core/src/main/scala/chisel3/Mem.scala @@ -35,6 +35,7 @@ object Mem { } val mt = t.cloneTypeFull val mem = new Mem(mt, size) + mt.bind(MemTypeBinding(mem)) pushCommand(DefMemory(sourceInfo, mem, mt, size)) mem } @@ -45,6 +46,8 @@ object Mem { } sealed abstract class MemBase[T <: Data](val t: T, val length: BigInt) extends HasId with NamedComponent with SourceInfoDoc { + _parent.foreach(_.addId(this)) + // REVIEW TODO: make accessors (static/dynamic, read/write) combinations consistent. /** Creates a read accessor into the memory with static addressing. See the @@ -174,6 +177,7 @@ object SyncReadMem { } val mt = t.cloneTypeFull val mem = new SyncReadMem(mt, size, ruw) + mt.bind(MemTypeBinding(mem)) pushCommand(DefSeqMemory(sourceInfo, mem, mt, size, ruw)) mem } diff --git a/core/src/main/scala/chisel3/Module.scala b/core/src/main/scala/chisel3/Module.scala index d34211f1..9f8087bf 100644 --- a/core/src/main/scala/chisel3/Module.scala +++ b/core/src/main/scala/chisel3/Module.scala @@ -209,6 +209,8 @@ package experimental { */ // TODO: seal this? abstract class BaseModule extends HasId { + _parent.foreach(_.addId(this)) + // // Builder Internals - this tracks which Module RTL construction belongs to. // @@ -382,6 +384,17 @@ package experimental { names } + /** Invokes _onModuleClose on HasIds found via reflection but not bound to hardware + * (thus not part of _ids) + * This maintains old naming behavior for non-hardware Data + */ + private[chisel3] def closeUnboundIds(names: HashMap[HasId, String]): Unit = { + val idLookup = _ids.toSet + for ((id, _) <- names if !idLookup(id)) { + id._onModuleClose + } + } + /** Compatibility function. Allows Chisel2 code which had ports without the IO wrapper to * compile under Bindings checks. Does nothing in non-compatibility mode. * diff --git a/core/src/main/scala/chisel3/RawModule.scala b/core/src/main/scala/chisel3/RawModule.scala index 0adacedb..d2ba6e84 100644 --- a/core/src/main/scala/chisel3/RawModule.scala +++ b/core/src/main/scala/chisel3/RawModule.scala @@ -98,6 +98,8 @@ abstract class RawModule(implicit moduleCompileOptions: CompileOptions) id._onModuleClose } + closeUnboundIds(names) + val firrtlPorts = getModulePorts map { port: Data => // Special case Vec to make FIRRTL emit the direction of its // element. diff --git a/core/src/main/scala/chisel3/experimental/Analog.scala b/core/src/main/scala/chisel3/experimental/Analog.scala index df76fd70..2ce2c86d 100644 --- a/core/src/main/scala/chisel3/experimental/Analog.scala +++ b/core/src/main/scala/chisel3/experimental/Analog.scala @@ -45,7 +45,8 @@ final class Analog private (private[chisel3] val width: Width) extends Element { // Define setter/getter pairing // Analog can only be bound to Ports and Wires (and Unbound) - private[chisel3] override def bind(target: Binding, parentDirection: SpecifiedDirection) { + private[chisel3] override def bind(target: Binding, parentDirection: SpecifiedDirection): Unit = { + _parent.foreach(_.addId(this)) SpecifiedDirection.fromParent(parentDirection, specifiedDirection) match { case SpecifiedDirection.Unspecified | SpecifiedDirection.Flip => case x => throwException(s"Analog may not have explicit direction, got '$x'") diff --git a/core/src/main/scala/chisel3/internal/Binding.scala b/core/src/main/scala/chisel3/internal/Binding.scala index 4442c62e..9e17aded 100644 --- a/core/src/main/scala/chisel3/internal/Binding.scala +++ b/core/src/main/scala/chisel3/internal/Binding.scala @@ -110,6 +110,10 @@ case class ChildBinding(parent: Data) extends Binding { case class SampleElementBinding[T <: Data](parent: Vec[T]) extends Binding { def location = parent.topBinding.location } +/** Special binding for Mem types */ +case class MemTypeBinding[T <: Data](parent: MemBase[T]) extends Binding { + def location: Option[BaseModule] = parent._parent +} // A DontCare element has a specific Binding, somewhat like a literal. // It is a source (RHS). It may only be connected/applied to sinks. case class DontCareBinding() extends UnconstrainedBinding diff --git a/core/src/main/scala/chisel3/internal/Builder.scala b/core/src/main/scala/chisel3/internal/Builder.scala index b7772aea..31d4666c 100644 --- a/core/src/main/scala/chisel3/internal/Builder.scala +++ b/core/src/main/scala/chisel3/internal/Builder.scala @@ -84,7 +84,6 @@ trait InstanceId { private[chisel3] trait HasId extends InstanceId { private[chisel3] def _onModuleClose: Unit = {} private[chisel3] val _parent: Option[BaseModule] = Builder.currentModule - _parent.foreach(_.addId(this)) private[chisel3] val _id: Long = Builder.idGen.next -- cgit v1.2.3 From 2b5466c7773c8cd7a08c48aa00d9365cbb205fd2 Mon Sep 17 00:00:00 2001 From: Schuyler Eldridge Date: Wed, 10 Feb 2021 22:19:09 -0500 Subject: Fix stack trace trimming across Driver/ChiselStage (#1771) * Handle MemTypeBinding in Analog Signed-off-by: Schuyler Eldridge * Fix stack trace trimming across ChiselStage Fix bug in stack trace trimming behavior. Now, the following is what happens: 1. The Builder, if catching accumulated errors, will now throw a ChiselException with a Scala-trimmed Stack trace. Previously, this would throw the full excpetion. 2. The Elaborate phase handles stack trace trimming. By default, any Throwable thrown during elaboration will have its stack trace *mutably* trimmed and is rethrown. A logger.error is printed stating that there was an error during elaboration and how the user can turn on the full stack trace. If the --full-stacktrace option is on, then the Throwable is not caught and only the first logger.error (saying that elaboration failed) will be printed. 3. ChiselStage (the class), ChiselStage$ (the object), and ChiselMain all inherit the behavior of (2). Mutable stack trace trimming behavior is moved into an implicit class (previously this was defined on ChiselException only) so this can be applied to any Throwable. No StageErrors are now thrown anymore. However, StageErrors may still be caught by ChiselMain (since it is a StageMain). Testing is added for ChiselMain, ChiselStage, and ChiselStage$ to test all this behavior. Signed-off-by: Schuyler Eldridge --- .../main/scala/chisel3/experimental/Analog.scala | 2 +- core/src/main/scala/chisel3/internal/Error.scala | 77 +++++++++++++++++++++- 2 files changed, 75 insertions(+), 4 deletions(-) (limited to 'core/src') diff --git a/core/src/main/scala/chisel3/experimental/Analog.scala b/core/src/main/scala/chisel3/experimental/Analog.scala index 2ce2c86d..6cca81f5 100644 --- a/core/src/main/scala/chisel3/experimental/Analog.scala +++ b/core/src/main/scala/chisel3/experimental/Analog.scala @@ -56,6 +56,7 @@ final class Analog private (private[chisel3] val width: Width) extends Element { case ChildBinding(parent) => parent.topBinding // See https://github.com/freechipsproject/chisel3/pull/946 case SampleElementBinding(parent) => parent.topBinding + case a: MemTypeBinding[_] => a } targetTopBinding match { @@ -83,4 +84,3 @@ final class Analog private (private[chisel3] val width: Width) extends Element { object Analog { def apply(width: Width): Analog = new Analog(width) } - diff --git a/core/src/main/scala/chisel3/internal/Error.scala b/core/src/main/scala/chisel3/internal/Error.scala index 60bb6e2b..134f4c87 100644 --- a/core/src/main/scala/chisel3/internal/Error.scala +++ b/core/src/main/scala/chisel3/internal/Error.scala @@ -5,12 +5,82 @@ package chisel3.internal import scala.annotation.tailrec import scala.collection.mutable.{ArrayBuffer, LinkedHashMap} -class ChiselException(message: String, cause: Throwable = null) extends Exception(message, cause) { +object ExceptionHelpers { + + /** Root packages that are not typically relevant to Chisel user code. */ + final val packageTrimlist: Set[String] = Set("chisel3", "scala", "java", "jdk", "sun", "sbt") + + /** The object name of Chisel's internal `Builder`. */ + final val builderName: String = chisel3.internal.Builder.getClass.getName + + /** Return a stack trace element that looks like `... (someMessage)`. + * @param message an optional message to include + */ + def ellipsis(message: Option[String] = None): StackTraceElement = + new StackTraceElement("..", " ", message.getOrElse(""), -1) + + /** Utility methods that can be added to exceptions. + */ + implicit class ThrowableHelpers(throwable: Throwable) { + + /** For an exception, mutably trim a stack trace to user code only. + * + * This does the following actions to the stack trace: + * + * 1. From the top, remove elements while the (root) package matches the packageTrimlist + * 2. Optionally, from the bottom, remove elements until the class matches an anchor + * 3. From the anchor (or the bottom), remove elements while the (root) package matches the packageTrimlist + * + * @param packageTrimlist packages that should be removed from the stack trace + * @param anchor an optional class name at which user execution might begin, e.g., a main object + * @return nothing as this mutates the exception directly + */ + def trimStackTraceToUserCode( + packageTrimlist: Set[String] = packageTrimlist, + anchor: Option[String] = Some(builderName) + ): Unit = { + def inTrimlist(ste: StackTraceElement) = { + val packageName = ste.getClassName().takeWhile(_ != '.') + packageTrimlist.contains(packageName) + } + + // Step 1: Remove elements from the top in the package trimlist + ((a: Array[StackTraceElement]) => a.view.dropWhile(inTrimlist)) + // Step 2: Optionally remove elements from the bottom until the anchor + .andThen(_.reverse) + .andThen( a => + anchor match { + case Some(b) => a.dropWhile(ste => !ste.getClassName.startsWith(b)) + case None => a + } + ) + // Step 3: Remove elements from the bottom in the package trimlist + .andThen(_.dropWhile(inTrimlist)) + // Step 4: Reverse back to the original order + .andThen(_.reverse.toArray) + // Step 5: Add ellipsis stack trace elements and "--full-stacktrace" info + .andThen(a => + ellipsis() +: + a :+ + ellipsis() :+ + ellipsis(Some("Stack trace trimmed to user code only. Rerun with --full-stacktrace to see the full stack trace"))) + // Step 5: Mutate the stack trace in this exception + .andThen(throwable.setStackTrace(_)) + .apply(throwable.getStackTrace) + } + + } + +} + +class ChiselException(message: String, cause: Throwable = null) extends Exception(message, cause, true, true) { /** Package names whose stack trace elements should be trimmed when generating a trimmed stack trace */ + @deprecated("Use ExceptionHelpers.packageTrimlist. This will be removed in Chisel 3.6", "3.5") val blacklistPackages: Set[String] = Set("chisel3", "scala", "java", "sun", "sbt") /** The object name of Chisel's internal `Builder`. Everything stack trace element after this will be trimmed. */ + @deprecated("Use ExceptionHelpers.builderName. This will be removed in Chisel 3.6", "3.5") val builderName: String = chisel3.internal.Builder.getClass.getName /** Examine a [[Throwable]], to extract all its causes. Innermost cause is first. @@ -27,7 +97,7 @@ class ChiselException(message: String, cause: Throwable = null) extends Exceptio /** Returns true if an exception contains */ private def containsBuilder(throwable: Throwable): Boolean = throwable.getStackTrace().collectFirst { - case ste if ste.getClassName().startsWith(builderName) => throwable + case ste if ste.getClassName().startsWith(ExceptionHelpers.builderName) => throwable }.isDefined /** Examine this [[ChiselException]] and it's causes for the first [[Throwable]] that contains a stack trace including @@ -142,7 +212,8 @@ private[chisel3] class ErrorLog { } if (!allErrors.isEmpty) { - throwException("Fatal errors during hardware elaboration") + throw new ChiselException("Fatal errors during hardware elaboration. Look above for error list.") + with scala.util.control.NoStackTrace } else { // No fatal errors, clear accumulated warnings since they've been reported errors.clear() -- cgit v1.2.3 From c2ba4098d0a2f7ca056ea198d68b1d3bfaf40f3b Mon Sep 17 00:00:00 2001 From: edwardcwang Date: Tue, 23 Feb 2021 22:29:33 -0500 Subject: Aggregate: fix typo (#1789) Not a Pokémon--- core/src/main/scala/chisel3/Aggregate.scala | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'core/src') diff --git a/core/src/main/scala/chisel3/Aggregate.scala b/core/src/main/scala/chisel3/Aggregate.scala index f07b2543..6942313e 100644 --- a/core/src/main/scala/chisel3/Aggregate.scala +++ b/core/src/main/scala/chisel3/Aggregate.scala @@ -521,7 +521,7 @@ abstract class Record(private[chisel3] implicit val compileOptions: CompileOptio * val b = Bool() * } * - * (mew MyBundle).Lit( + * (new MyBundle).Lit( * _.a -> 42.U, * _.b -> true.B * ) -- cgit v1.2.3 From 923ccbde1353e37f0948d3c5d94b49965dc6d950 Mon Sep 17 00:00:00 2001 From: Jiuyang Liu Date: Sat, 27 Feb 2021 05:01:10 +0800 Subject: Expose AnnotationSeq to Module. (#1731) --- core/src/main/scala/chisel3/Module.scala | 1 + core/src/main/scala/chisel3/aop/Aspect.scala | 7 ++++++- core/src/main/scala/chisel3/internal/Builder.scala | 11 ++++------- 3 files changed, 11 insertions(+), 8 deletions(-) (limited to 'core/src') diff --git a/core/src/main/scala/chisel3/Module.scala b/core/src/main/scala/chisel3/Module.scala index 9f8087bf..ede9ccc6 100644 --- a/core/src/main/scala/chisel3/Module.scala +++ b/core/src/main/scala/chisel3/Module.scala @@ -14,6 +14,7 @@ import chisel3.internal.firrtl._ import chisel3.internal.sourceinfo.{InstTransform, SourceInfo, UnlocatableSourceInfo} import chisel3.experimental.BaseModule import _root_.firrtl.annotations.{IsModule, ModuleName, ModuleTarget} +import _root_.firrtl.AnnotationSeq object Module extends SourceInfoDoc { /** A wrapper method that all Module instantiations must be wrapped in diff --git a/core/src/main/scala/chisel3/aop/Aspect.scala b/core/src/main/scala/chisel3/aop/Aspect.scala index 59add417..be9b8975 100644 --- a/core/src/main/scala/chisel3/aop/Aspect.scala +++ b/core/src/main/scala/chisel3/aop/Aspect.scala @@ -12,6 +12,10 @@ import firrtl.AnnotationSeq * @tparam T Type of top-level module */ abstract class Aspect[T <: RawModule] extends Annotation with Unserializable with NoTargetAnnotation { + /** variable to save [[AnnotationSeq]] from [[chisel3.stage.phases.AspectPhase]] + * to be used at [[chisel3.aop.injecting.InjectorAspect]], exposes annotations to [[chisel3.internal.DynamicContext]] + */ + private[aop] var annotationsInAspect: AnnotationSeq = Seq() /** Convert this Aspect to a seq of FIRRTL annotation * @param top * @return @@ -22,7 +26,8 @@ abstract class Aspect[T <: RawModule] extends Annotation with Unserializable wit * @param top * @return */ - private[chisel3] def resolveAspect(top: RawModule): AnnotationSeq = { + private[chisel3] def resolveAspect(top: RawModule, remainingAnnotations: AnnotationSeq): AnnotationSeq = { + annotationsInAspect = remainingAnnotations toAnnotation(top.asInstanceOf[T]) } } diff --git a/core/src/main/scala/chisel3/internal/Builder.scala b/core/src/main/scala/chisel3/internal/Builder.scala index 31d4666c..e95384cd 100644 --- a/core/src/main/scala/chisel3/internal/Builder.scala +++ b/core/src/main/scala/chisel3/internal/Builder.scala @@ -9,7 +9,8 @@ import chisel3.experimental._ import chisel3.internal.firrtl._ import chisel3.internal.naming._ import _root_.firrtl.annotations.{CircuitName, ComponentName, IsMember, ModuleName, Named, ReferenceTarget} -import _root_.firrtl.annotations.AnnotationUtils.{validComponentName} +import _root_.firrtl.annotations.AnnotationUtils.validComponentName +import _root_.firrtl.AnnotationSeq import chisel3.internal.Builder.Prefix import logger.LazyLogging @@ -305,7 +306,7 @@ private[chisel3] class ChiselContext() { var prefixStack: Prefix = Nil } -private[chisel3] class DynamicContext() { +private[chisel3] class DynamicContext(val annotationSeq: AnnotationSeq) { val globalNamespace = Namespace.empty val components = ArrayBuffer[Component]() val annotations = ArrayBuffer[ChiselAnnotation]() @@ -364,6 +365,7 @@ private[chisel3] object Builder extends LazyLogging { def globalNamespace: Namespace = dynamicContext.globalNamespace def components: ArrayBuffer[Component] = dynamicContext.components def annotations: ArrayBuffer[ChiselAnnotation] = dynamicContext.annotations + def annotationSeq: AnnotationSeq = dynamicContext.annotationSeq def namingStack: NamingStack = dynamicContext.namingStack // Puts a prefix string onto the prefix stack @@ -632,11 +634,6 @@ private[chisel3] object Builder extends LazyLogging { } } - - def build[T <: RawModule](f: => T): (Circuit, T) = { - build(f, new DynamicContext()) - } - private [chisel3] def build[T <: RawModule](f: => T, dynamicContext: DynamicContext): (Circuit, T) = { dynamicContextVar.withValue(Some(dynamicContext)) { checkScalaVersion() -- cgit v1.2.3 From 1494231212425fd09f915d819102ca5cdef0dfcf Mon Sep 17 00:00:00 2001 From: Jack Koenig Date: Thu, 11 Feb 2021 18:12:48 -0800 Subject: [plugin] Implement autoclonetype in the compiler plugin --- core/src/main/scala/chisel3/Aggregate.scala | 56 ++++++++++++++++------ core/src/main/scala/chisel3/internal/Builder.scala | 8 ++++ 2 files changed, 50 insertions(+), 14 deletions(-) (limited to 'core/src') diff --git a/core/src/main/scala/chisel3/Aggregate.scala b/core/src/main/scala/chisel3/Aggregate.scala index 6942313e..30276230 100644 --- a/core/src/main/scala/chisel3/Aggregate.scala +++ b/core/src/main/scala/chisel3/Aggregate.scala @@ -798,6 +798,13 @@ abstract class Bundle(implicit compileOptions: CompileOptions) extends Record { case _ => None } + /** Indicates if a concrete Bundle class was compiled using the compiler plugin + * + * Used for optimizing Chisel's performance and testing Chisel itself + * @note This should not be used in user code! + */ + protected def _usingPlugin: Boolean = false + // Memoize the outer instance for autoclonetype, especially where this is context-dependent // (like the outer module or enclosing Bundles). private var _outerInst: Option[Object] = None @@ -808,7 +815,33 @@ abstract class Bundle(implicit compileOptions: CompileOptions) extends Record { private val _containingModule: Option[BaseModule] = Builder.currentModule private val _containingBundles: Seq[Bundle] = Builder.updateBundleStack(this) - override def cloneType : this.type = { + private def checkClone(clone: Bundle): Unit = { + for ((name, field) <- elements) { + if (clone.elements(name) eq field) { + throw new AutoClonetypeException( + s"Automatically cloned $clone has field '$name' aliased with base $this." + + " In the future, this will be solved automatically by the compiler plugin." + + " For now, ensure Chisel types used in the Bundle definition are passed through constructor arguments," + + " or wrapped in Input(...), Output(...), or Flipped(...) if appropriate." + + " As a last resort, you can override cloneType manually." + ) + } + } + + } + + override def cloneType: this.type = { + val clone = _cloneTypeImpl.asInstanceOf[this.type] + checkClone(clone) + clone + } + + /** Implementation of cloneType using runtime reflection. This should _never_ be overridden or called in user-code + * + * @note This is overridden by the compiler plugin (it is never called when using the plugin) + */ + protected def _cloneTypeImpl: Bundle = { + assert(Builder.allowReflectiveAutoCloneType, "reflective autoclonetype is disallowed, this should only happen in testing") // This attempts to infer constructor and arguments to clone this Bundle subtype without // requiring the user explicitly overriding cloneType. import scala.language.existentials @@ -816,24 +849,19 @@ abstract class Bundle(implicit compileOptions: CompileOptions) extends Record { val clazz = this.getClass - def autoClonetypeError(desc: String): Nothing = { - throw new AutoClonetypeException(s"Unable to automatically infer cloneType on $clazz: $desc") - } + def autoClonetypeError(desc: String): Nothing = + throw new AutoClonetypeException( + s"Unable to automatically infer cloneType on $clazz. " + + "cloneType is now implemented by the Chisel compiler plugin so please ensure you are using it in your build. " + + "If you cannot use the compiler plugin or you are using it and you still see this message, please file an issue and let us know. " + + s"For those not using the plugin, here is the 'runtime reflection' cloneType error message: $desc" + ) def validateClone(clone: Bundle, equivDiagnostic: String): Unit = { if (!clone.typeEquivalent(this)) { autoClonetypeError(s"Automatically cloned $clone not type-equivalent to base $this. " + equivDiagnostic) } - - for ((name, field) <- elements) { - if (clone.elements(name) eq field) { - autoClonetypeError(s"Automatically cloned $clone has field $name aliased with base $this." + - " In the future, this can be solved by wrapping the field in Field(...)," + - " see https://github.com/freechipsproject/chisel3/pull/909." + - " For now, ensure Chisel types used in the Bundle definition are passed through constructor arguments," + - " or wrapped in Input(...), Output(...), or Flipped(...) if appropriate.") - } - } + checkClone(clone) } val mirror = runtimeMirror(clazz.getClassLoader) diff --git a/core/src/main/scala/chisel3/internal/Builder.scala b/core/src/main/scala/chisel3/internal/Builder.scala index e95384cd..b1016a2e 100644 --- a/core/src/main/scala/chisel3/internal/Builder.scala +++ b/core/src/main/scala/chisel3/internal/Builder.scala @@ -311,6 +311,8 @@ private[chisel3] class DynamicContext(val annotationSeq: AnnotationSeq) { val components = ArrayBuffer[Component]() val annotations = ArrayBuffer[ChiselAnnotation]() var currentModule: Option[BaseModule] = None + // This is only used for testing, it can be removed if the plugin becomes mandatory + var allowReflectiveAutoCloneType = true /** Contains a mapping from a elaborated module to their aspect * Set by [[ModuleAspect]] @@ -530,6 +532,12 @@ private[chisel3] object Builder extends LazyLogging { dynamicContext.currentReset = newReset } + // This should only be used for testing + def allowReflectiveAutoCloneType: Boolean = dynamicContext.allowReflectiveAutoCloneType + def allowReflectiveAutoCloneType_=(value: Boolean): Unit = { + dynamicContext.allowReflectiveAutoCloneType = value + } + def forcedClock: Clock = currentClock.getOrElse( throwException("Error: No implicit clock.") ) -- cgit v1.2.3 From a8d32388ffa8c29a3b0f9e78ab6cd917b92954cd Mon Sep 17 00:00:00 2001 From: Jack Koenig Date: Thu, 4 Mar 2021 18:24:08 -0800 Subject: [plugin] Stop autoclonetype stack traces when using plugin The compiler plugin obviates the need for using stack traces to determine outer objects in autoclonetype. When the plugin was used to compile a given Bundle, it will no longer collect a stack trace upon construction. This should have massive benefits to elaboration runtime. --- core/src/main/scala/chisel3/Aggregate.scala | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'core/src') diff --git a/core/src/main/scala/chisel3/Aggregate.scala b/core/src/main/scala/chisel3/Aggregate.scala index 30276230..c5a917fa 100644 --- a/core/src/main/scala/chisel3/Aggregate.scala +++ b/core/src/main/scala/chisel3/Aggregate.scala @@ -809,11 +809,11 @@ abstract class Bundle(implicit compileOptions: CompileOptions) extends Record { // (like the outer module or enclosing Bundles). private var _outerInst: Option[Object] = None - // For autoclonetype, record possible candidates for outer instance. + // For reflective autoclonetype, record possible candidates for outer instance. // _outerInst should always take precedence, since it should be propagated from the original // object which has the most accurate context. - private val _containingModule: Option[BaseModule] = Builder.currentModule - private val _containingBundles: Seq[Bundle] = Builder.updateBundleStack(this) + private val _containingModule: Option[BaseModule] = if (_usingPlugin) None else Builder.currentModule + private val _containingBundles: Seq[Bundle] = if (_usingPlugin) Nil else Builder.updateBundleStack(this) private def checkClone(clone: Bundle): Unit = { for ((name, field) <- elements) { -- cgit v1.2.3 From 96436ae018b3631decb8384ce404ada0daa5d645 Mon Sep 17 00:00:00 2001 From: Jack Koenig Date: Mon, 15 Mar 2021 16:55:06 -0700 Subject: allowReflectiveAutoCloneType must work outside of Builder context (#1811) --- core/src/main/scala/chisel3/internal/Builder.scala | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) (limited to 'core/src') diff --git a/core/src/main/scala/chisel3/internal/Builder.scala b/core/src/main/scala/chisel3/internal/Builder.scala index b1016a2e..084bdc88 100644 --- a/core/src/main/scala/chisel3/internal/Builder.scala +++ b/core/src/main/scala/chisel3/internal/Builder.scala @@ -532,8 +532,12 @@ private[chisel3] object Builder extends LazyLogging { dynamicContext.currentReset = newReset } - // This should only be used for testing - def allowReflectiveAutoCloneType: Boolean = dynamicContext.allowReflectiveAutoCloneType + // This should only be used for testing, must be true outside of Builder context + def allowReflectiveAutoCloneType: Boolean = { + dynamicContextVar.value + .map(_.allowReflectiveAutoCloneType) + .getOrElse(true) + } def allowReflectiveAutoCloneType_=(value: Boolean): Unit = { dynamicContext.allowReflectiveAutoCloneType = value } -- cgit v1.2.3 From 9c9bc131b031764332aeb2b175ae8abc500b8801 Mon Sep 17 00:00:00 2001 From: Jack Koenig Date: Mon, 29 Mar 2021 14:56:22 -0700 Subject: Provide useful message on Vec.apply require (#1838) --- core/src/main/scala/chisel3/Aggregate.scala | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'core/src') diff --git a/core/src/main/scala/chisel3/Aggregate.scala b/core/src/main/scala/chisel3/Aggregate.scala index c5a917fa..df992bb9 100644 --- a/core/src/main/scala/chisel3/Aggregate.scala +++ b/core/src/main/scala/chisel3/Aggregate.scala @@ -342,7 +342,7 @@ object VecInit extends SourceInfoDoc { // DummyImplicit or additional type parameter will break some code. // Check that types are homogeneous. Width mismatch for Elements is safe. - require(!elts.isEmpty) + require(elts.nonEmpty, "Vec hardware values are not allowed to be empty") elts.foreach(requireIsHardware(_, "vec element")) val vec = Wire(Vec(elts.length, cloneSupertype(elts, "Vec"))) -- cgit v1.2.3 From c71428023749b22718016f37fe68f5ddd358b5fe Mon Sep 17 00:00:00 2001 From: Jack Koenig Date: Mon, 26 Apr 2021 15:39:54 -0700 Subject: Add some error context to Converter .getRefs (#1878) --- .../scala/chisel3/internal/firrtl/Converter.scala | 87 +++++++++++++--------- 1 file changed, 51 insertions(+), 36 deletions(-) (limited to 'core/src') diff --git a/core/src/main/scala/chisel3/internal/firrtl/Converter.scala b/core/src/main/scala/chisel3/internal/firrtl/Converter.scala index aefbf8ab..ff0fa770 100644 --- a/core/src/main/scala/chisel3/internal/firrtl/Converter.scala +++ b/core/src/main/scala/chisel3/internal/firrtl/Converter.scala @@ -3,9 +3,9 @@ package chisel3.internal.firrtl import chisel3._ import chisel3.experimental._ -import chisel3.internal.sourceinfo.{NoSourceInfo, SourceLine, SourceInfo} +import chisel3.internal.sourceinfo.{NoSourceInfo, SourceInfo, SourceLine, UnlocatableSourceInfo} import firrtl.{ir => fir} -import chisel3.internal.{castToInt, throwException} +import chisel3.internal.{HasId, castToInt, throwException} import scala.annotation.tailrec import scala.collection.immutable.Queue @@ -24,6 +24,16 @@ private[chisel3] object Converter { case Percent => ("%%", List.empty) } + def getRef(id: HasId, sourceInfo: SourceInfo): Arg = + id.getOptionRef.getOrElse { + val module = id._parent.map(m => s" '$id' was defined in module '$m'.").getOrElse("") + val loc = sourceInfo.makeMessage(" " + _) + val link = "https://github.com/chipsalliance/chisel3/issues/new" + val msg = s"Internal error! Could not get ref for '$id'$loc!$module " + + s"This is a bug in Chisel, please file an issue at '$link'." + throwException(msg) + } + def convert(info: SourceInfo): fir.Info = info match { case _: NoSourceInfo => fir.NoInfo case SourceLine(fn, line, col) => fir.FileInfo(fir.StringLit(s"$fn $line:$col")) @@ -41,37 +51,37 @@ private[chisel3] object Converter { // TODO // * Memoize? // * Move into the Chisel IR? - def convert(arg: Arg, ctx: Component): fir.Expression = arg match { + def convert(arg: Arg, ctx: Component, info: SourceInfo): fir.Expression = arg match { case Node(id) => - convert(id.getRef, ctx) + convert(getRef(id, info), ctx, info) case Ref(name) => fir.Reference(name, fir.UnknownType) case Slot(imm, name) => - fir.SubField(convert(imm, ctx), name, fir.UnknownType) + fir.SubField(convert(imm, ctx, info), name, fir.UnknownType) case Index(imm, ILit(idx)) => - fir.SubIndex(convert(imm, ctx), castToInt(idx, "Index"), fir.UnknownType) + fir.SubIndex(convert(imm, ctx, info), castToInt(idx, "Index"), fir.UnknownType) case Index(imm, value) => - fir.SubAccess(convert(imm, ctx), convert(value, ctx), fir.UnknownType) + fir.SubAccess(convert(imm, ctx, info), convert(value, ctx, info), fir.UnknownType) case ModuleIO(mod, name) => if (mod eq ctx.id) fir.Reference(name, fir.UnknownType) - else fir.SubField(fir.Reference(mod.getRef.name, fir.UnknownType), name, fir.UnknownType) + else fir.SubField(fir.Reference(getRef(mod, info).name, fir.UnknownType), name, fir.UnknownType) case u @ ULit(n, UnknownWidth()) => fir.UIntLiteral(n, fir.IntWidth(u.minWidth)) case ULit(n, w) => fir.UIntLiteral(n, convert(w)) case slit @ SLit(n, w) => fir.SIntLiteral(n, convert(w)) val unsigned = if (n < 0) (BigInt(1) << slit.width.get) + n else n - val uint = convert(ULit(unsigned, slit.width), ctx) + val uint = convert(ULit(unsigned, slit.width), ctx, info) fir.DoPrim(firrtl.PrimOps.AsSInt, Seq(uint), Seq.empty, fir.UnknownType) // TODO Simplify case fplit @ FPLit(n, w, bp) => val unsigned = if (n < 0) (BigInt(1) << fplit.width.get) + n else n - val uint = convert(ULit(unsigned, fplit.width), ctx) + val uint = convert(ULit(unsigned, fplit.width), ctx, info) val lit = bp.asInstanceOf[KnownBinaryPoint].value fir.DoPrim(firrtl.PrimOps.AsFixedPoint, Seq(uint), Seq(lit), fir.UnknownType) case intervalLit @ IntervalLit(n, w, bp) => val unsigned = if (n < 0) (BigInt(1) << intervalLit.width.get) + n else n - val uint = convert(ULit(unsigned, intervalLit.width), ctx) + val uint = convert(ULit(unsigned, intervalLit.width), ctx, info) val lit = bp.asInstanceOf[KnownBinaryPoint].value fir.DoPrim(firrtl.PrimOps.AsInterval, Seq(uint), Seq(n, n, lit), fir.UnknownType) case lit: ILit => @@ -84,7 +94,7 @@ private[chisel3] object Converter { val consts = e.args.collect { case ILit(i) => i } val args = e.args.flatMap { case _: ILit => None - case other => Some(convert(other, ctx)) + case other => Some(convert(other, ctx, e.sourceInfo)) } val expr = e.op.name match { case "mux" => @@ -95,44 +105,45 @@ private[chisel3] object Converter { } Some(fir.DefNode(convert(e.sourceInfo), e.name, expr)) case e @ DefWire(info, id) => - Some(fir.DefWire(convert(info), e.name, extractType(id))) + Some(fir.DefWire(convert(info), e.name, extractType(id, info))) case e @ DefReg(info, id, clock) => - Some(fir.DefRegister(convert(info), e.name, extractType(id), convert(clock, ctx), - firrtl.Utils.zero, convert(id.getRef, ctx))) + Some(fir.DefRegister(convert(info), e.name, extractType(id, info), convert(clock, ctx, info), + firrtl.Utils.zero, convert(getRef(id, info), ctx, info))) case e @ DefRegInit(info, id, clock, reset, init) => - Some(fir.DefRegister(convert(info), e.name, extractType(id), convert(clock, ctx), - convert(reset, ctx), convert(init, ctx))) + Some(fir.DefRegister(convert(info), e.name, extractType(id, info), convert(clock, ctx, info), + convert(reset, ctx, info), convert(init, ctx, info))) case e @ DefMemory(info, id, t, size) => - Some(firrtl.CDefMemory(convert(info), e.name, extractType(t), size, false)) + Some(firrtl.CDefMemory(convert(info), e.name, extractType(t, info), size, false)) case e @ DefSeqMemory(info, id, t, size, ruw) => - Some(firrtl.CDefMemory(convert(info), e.name, extractType(t), size, true, ruw)) + Some(firrtl.CDefMemory(convert(info), e.name, extractType(t, info), size, true, ruw)) case e: DefMemPort[_] => + val info = e.sourceInfo Some(firrtl.CDefMPort(convert(e.sourceInfo), e.name, fir.UnknownType, - e.source.fullName(ctx), Seq(convert(e.index, ctx), convert(e.clock, ctx)), convert(e.dir))) + e.source.fullName(ctx), Seq(convert(e.index, ctx, info), convert(e.clock, ctx, info)), convert(e.dir))) case Connect(info, loc, exp) => - Some(fir.Connect(convert(info), convert(loc, ctx), convert(exp, ctx))) + Some(fir.Connect(convert(info), convert(loc, ctx, info), convert(exp, ctx, info))) case BulkConnect(info, loc, exp) => - Some(fir.PartialConnect(convert(info), convert(loc, ctx), convert(exp, ctx))) + Some(fir.PartialConnect(convert(info), convert(loc, ctx, info), convert(exp, ctx, info))) case Attach(info, locs) => - Some(fir.Attach(convert(info), locs.map(l => convert(l, ctx)))) + Some(fir.Attach(convert(info), locs.map(l => convert(l, ctx, info)))) case DefInvalid(info, arg) => - Some(fir.IsInvalid(convert(info), convert(arg, ctx))) + Some(fir.IsInvalid(convert(info), convert(arg, ctx, info))) case e @ DefInstance(info, id, _) => Some(fir.DefInstance(convert(info), e.name, id.name)) case Stop(info, clock, ret) => - Some(fir.Stop(convert(info), ret, convert(clock, ctx), firrtl.Utils.one)) + Some(fir.Stop(convert(info), ret, convert(clock, ctx, info), firrtl.Utils.one)) case Printf(info, clock, pable) => val (fmt, args) = unpack(pable, ctx) Some(fir.Print(convert(info), fir.StringLit(fmt), - args.map(a => convert(a, ctx)), convert(clock, ctx), firrtl.Utils.one)) + args.map(a => convert(a, ctx, info)), convert(clock, ctx, info), firrtl.Utils.one)) case Verification(op, info, clk, pred, msg) => val firOp = op match { case Formal.Assert => fir.Formal.Assert case Formal.Assume => fir.Formal.Assume case Formal.Cover => fir.Formal.Cover } - Some(fir.Verification(firOp, convert(info), convert(clk, ctx), - convert(pred, ctx), firrtl.Utils.one, fir.StringLit(msg))) + Some(fir.Verification(firOp, convert(info), convert(clk, ctx, info), + convert(pred, ctx, info), firrtl.Utils.one, fir.StringLit(msg))) case _ => None } @@ -173,7 +184,7 @@ private[chisel3] object Converter { // Please see WhenFrame for more details case None => cmds.head match { case WhenBegin(info, pred) => - val when = fir.Conditionally(convert(info), convert(pred, ctx), fir.EmptyStmt, fir.EmptyStmt) + val when = fir.Conditionally(convert(info), convert(pred, ctx, info), fir.EmptyStmt, fir.EmptyStmt) val frame = WhenFrame(when, acc, false) rec(Queue.empty, frame +: scope)(cmds.tail) case WhenEnd(info, depth, _) => @@ -221,7 +232,9 @@ private[chisel3] object Converter { case d => d.specifiedDirection } - def extractType(data: Data, clearDir: Boolean = false): fir.Type = data match { + def extractType(data: Data, info: SourceInfo): fir.Type = extractType(data, false, info) + + def extractType(data: Data, clearDir: Boolean, info: SourceInfo): fir.Type = data match { case _: Clock => fir.ClockType case _: AsyncReset => fir.AsyncResetType case _: ResetType => fir.ResetType @@ -231,16 +244,16 @@ private[chisel3] object Converter { case d: FixedPoint => fir.FixedType(convert(d.width), convert(d.binaryPoint)) case d: Interval => fir.IntervalType(d.range.lowerBound, d.range.upperBound, d.range.firrtlBinaryPoint) case d: Analog => fir.AnalogType(convert(d.width)) - case d: Vec[_] => fir.VectorType(extractType(d.sample_element, clearDir), d.length) + case d: Vec[_] => fir.VectorType(extractType(d.sample_element, clearDir, info), d.length) case d: Record => val childClearDir = clearDir || d.specifiedDirection == SpecifiedDirection.Input || d.specifiedDirection == SpecifiedDirection.Output def eltField(elt: Data): fir.Field = (childClearDir, firrtlUserDirOf(elt)) match { - case (true, _) => fir.Field(elt.getRef.name, fir.Default, extractType(elt, true)) + case (true, _) => fir.Field(getRef(elt, info).name, fir.Default, extractType(elt, true, info)) case (false, SpecifiedDirection.Unspecified | SpecifiedDirection.Output) => - fir.Field(elt.getRef.name, fir.Default, extractType(elt, false)) + fir.Field(getRef(elt, info).name, fir.Default, extractType(elt, false, info)) case (false, SpecifiedDirection.Flip | SpecifiedDirection.Input) => - fir.Field(elt.getRef.name, fir.Flip, extractType(elt, false)) + fir.Field(getRef(elt, info).name, fir.Flip, extractType(elt, false, info)) } fir.BundleType(d.elements.toIndexedSeq.reverse.map { case (_, e) => eltField(e) }) } @@ -251,6 +264,7 @@ private[chisel3] object Converter { case StringParam(value) => fir.StringParam(name, fir.StringLit(value)) case RawParam(value) => fir.RawStringParam(name, value) } + def convert(port: Port, topDir: SpecifiedDirection = SpecifiedDirection.Unspecified): fir.Port = { val resolvedDir = SpecifiedDirection.fromParent(topDir, port.dir) val dir = resolvedDir match { @@ -261,8 +275,9 @@ private[chisel3] object Converter { case SpecifiedDirection.Input | SpecifiedDirection.Output => true case SpecifiedDirection.Unspecified | SpecifiedDirection.Flip => false } - val tpe = extractType(port.id, clearDir) - fir.Port(fir.NoInfo, port.id.getRef.name, dir, tpe) + val info = UnlocatableSourceInfo // Unfortunately there is no source locator for ports ATM + val tpe = extractType(port.id, clearDir, info) + fir.Port(fir.NoInfo, getRef(port.id, info).name, dir, tpe) } def convert(component: Component): fir.DefModule = component match { -- cgit v1.2.3 From 6deb379b1d8bafc81a605f60476bf0f24eac60b4 Mon Sep 17 00:00:00 2001 From: Chick Markley Date: Tue, 27 Apr 2021 12:17:17 -0700 Subject: Introduce VecLiterals (#1834) This PR provides for support for Vec literals. They can be one of two forms Inferred: ``` Vec.Lit(0x1.U, 0x2.U) ``` or explicit: ``` Vec(2, UInt(4.W)).Lit(0 -> 0x1.U, 1 -> 0x2.U) ``` - Explicit form allows for partial, or sparse, literals. - Vec literals can be used as Register initializers - Arbitrary nesting (consistent with type constraints is allowed)--- core/src/main/scala/chisel3/Aggregate.scala | 274 ++++++++++++++++++--- core/src/main/scala/chisel3/Data.scala | 6 + core/src/main/scala/chisel3/Element.scala | 4 + .../main/scala/chisel3/experimental/package.scala | 33 ++- core/src/main/scala/chisel3/internal/Binding.scala | 4 + .../main/scala/chisel3/internal/firrtl/IR.scala | 24 ++ 6 files changed, 309 insertions(+), 36 deletions(-) (limited to 'core/src') diff --git a/core/src/main/scala/chisel3/Aggregate.scala b/core/src/main/scala/chisel3/Aggregate.scala index df992bb9..c0b965b6 100644 --- a/core/src/main/scala/chisel3/Aggregate.scala +++ b/core/src/main/scala/chisel3/Aggregate.scala @@ -2,18 +2,19 @@ package chisel3 +import chisel3.experimental.VecLiterals.AddVecLiteralConstructor + import scala.collection.immutable.ListMap import scala.collection.mutable.{HashSet, LinkedHashMap} import scala.language.experimental.macros - -import chisel3.experimental.BaseModule -import chisel3.experimental.BundleLiteralException -import chisel3.experimental.EnumType +import chisel3.experimental.{BaseModule, BundleLiteralException, ChiselEnum, EnumType, VecLiteralException} import chisel3.internal._ import chisel3.internal.Builder.pushCommand import chisel3.internal.firrtl._ import chisel3.internal.sourceinfo._ +import scala.collection.mutable + class AliasedAggregateFieldException(message: String) extends ChiselException(message) /** An abstract class for data types that solely consist of (are an aggregate @@ -51,16 +52,19 @@ sealed abstract class Aggregate extends Data { */ override def litOption: Option[BigInt] = { // Shift the accumulated value by our width and add in our component, masked by our width. - def shiftAdd(accumulator: Option[BigInt], elt: Data): Option[BigInt] = (accumulator, elt.litOption()) match { - case (Some(accumulator), Some(eltLit)) => - val width = elt.width.get - val masked = ((BigInt(1) << width) - 1) & eltLit // also handles the negative case with two's complement - Some((accumulator << width) + masked) - case (None, _) => None - case (_, None) => None + def shiftAdd(accumulator: Option[BigInt], elt: Data): Option[BigInt] = { + (accumulator, elt.litOption()) match { + case (Some(accumulator), Some(eltLit)) => + val width = elt.width.get + val masked = ((BigInt(1) << width) - 1) & eltLit // also handles the negative case with two's complement + Some((accumulator << width) + masked) + case (None, _) => None + case (_, None) => None + } } + topBindingOpt match { - case Some(BundleLitBinding(_)) => + case Some(BundleLitBinding(_)) | Some(VecLitBinding(_)) => getElements .reverse .foldLeft[Option[BigInt]](Some(BigInt(0)))(shiftAdd) @@ -73,6 +77,7 @@ sealed abstract class Aggregate extends Data { def getElements: Seq[Data] private[chisel3] def width: Width = getElements.map(_.width).foldLeft(0.W)(_ + _) + private[chisel3] def legacyConnect(that: Data)(implicit sourceInfo: SourceInfo): Unit = { // If the source is a DontCare, generate a DefInvalid for the sink, // otherwise, issue a Connect. @@ -83,11 +88,50 @@ sealed abstract class Aggregate extends Data { } } + // Returns pairs of all fields, element-level and containers, in a Record and their path names + private[chisel3] def getRecursiveFields(data: Data, path: String): Seq[(Data, String)] = data match { + case data: Record => + data.elements.map { case (fieldName, fieldData) => + getRecursiveFields(fieldData, s"$path.$fieldName") + }.fold(Seq(data -> path)) { + _ ++ _ + } + case data: Vec[_] => + data.getElements.zipWithIndex.map { case (fieldData, fieldIndex) => + getRecursiveFields(fieldData, path = s"$path($fieldIndex)") + }.fold(Seq(data -> path)) { + _ ++ _ + } + case data => Seq(data -> path) // we don't support or recurse into other Aggregate types here + } + + + // Returns pairs of corresponding fields between two Records of the same type + private[chisel3] def getMatchedFields(x: Data, y: Data): Seq[(Data, Data)] = (x, y) match { + case (x: Element, y: Element) => + require(x typeEquivalent y) + Seq(x -> y) + case (x: Record, y: Record) => + (x.elements zip y.elements).map { case ((xName, xElt), (yName, yElt)) => + require(xName == yName) // assume fields returned in same, deterministic order + getMatchedFields(xElt, yElt) + }.fold(Seq(x -> y)) { + _ ++ _ + } + case (x: Vec[_], y: Vec[_]) => + (x.getElements zip y.getElements).map { case (xElt, yElt) => + getMatchedFields(xElt, yElt) + }.fold(Seq(x -> y)) { + _ ++ _ + } + } + override def do_asUInt(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): UInt = { SeqUtils.do_asUInt(flatten.map(_.asUInt())) } + private[chisel3] override def connectFromBits(that: Bits)(implicit sourceInfo: SourceInfo, - compileOptions: CompileOptions): Unit = { + compileOptions: CompileOptions): Unit = { var i = 0 val bits = if (that.isLit) that else WireDefault(UInt(this.width), that) // handles width padding for (x <- flatten) { @@ -155,9 +199,18 @@ trait VecFactory extends SourceInfoDoc { */ sealed class Vec[T <: Data] private[chisel3] (gen: => T, val length: Int) extends Aggregate with VecLike[T] { + override def toString: String = { + val bindingString = topBindingOpt match { + case Some(VecLitBinding(vecLitBinding)) => + val contents = vecLitBinding.zipWithIndex.map { case ((data, lit), index) => + s"$index=$lit" + }.mkString(", ") + s"($contents)" + case _ => bindingToString + } val elementType = sample_element.cloneType - s"$elementType[$length]$bindingToString" + s"$elementType[$length]$bindingString" } private[chisel3] override def typeEquivalent(that: Data): Boolean = that match { @@ -318,6 +371,154 @@ sealed class Vec[T <: Data] private[chisel3] (gen: => T, val length: Int) } curLayer(0) } + + /** Creates a Vec literal of this type with specified values. this must be a chisel type. + * + * @param elementInitializers literal values, specified as a pair of the Vec field to the literal value. + * The Vec field is specified as a function from an object of this type to the field. + * Fields that aren't initialized to DontCare, and assignment to a wire will overwrite any + * existing value with DontCare. + * @return a Vec literal of this type with subelement values specified + * + * Vec(2, UInt(8.W)).Lit( + * 1 -> 0x0A.U, + * 2 -> 0x0B.U + * ) + * }}} + */ + private[chisel3] def _makeLit(elementInitializers: (Int, T)*)(implicit sourceInfo: SourceInfo, + compileOptions: CompileOptions): this.type = { + + def checkLiteralConstruction(): Unit = { + val dupKeys = elementInitializers.map { x => x._1 }.groupBy(x => x).flatMap { case (k, v) => + if (v.length > 1) { + Some(k, v.length) + } else { + None + } + } + if (dupKeys.nonEmpty) { + throw new VecLiteralException( + s"VecLiteral: has duplicated indices ${dupKeys.map { case (k, n) => s"$k($n times)" }.mkString(",")}" + ) + } + + val outOfRangeIndices = elementInitializers.map(_._1).filter { case index => index < 0 || index >= length } + if (outOfRangeIndices.nonEmpty) { + throw new VecLiteralException( + s"VecLiteral: The following indices (${outOfRangeIndices.mkString(",")}) " + + s"are less than zero or greater or equal to than Vec length" + ) + } + cloneSupertype(elementInitializers.map(_._2), s"Vec.Lit(...)") + + // look for literals of this vec that are wider than the vec's type + val badLits = elementInitializers.flatMap { + case (index, lit) => + (sample_element.width, lit.width) match { + case (KnownWidth(m), KnownWidth(n)) => + if (m < n) Some(index -> lit) else None + case (KnownWidth(_), _) => + None + case (UnknownWidth(), _) => + None + case _ => + Some(index -> lit) + } + case _ => None + } + if (badLits.nonEmpty) { + throw new VecLiteralException( + s"VecLiteral: Vec[$gen] has the following incorrectly typed or sized initializers: " + + badLits.map { case (a, b) => s"$a -> $b" }.mkString(",") + ) + } + + } + + requireIsChiselType(this, "vec literal constructor model") + checkLiteralConstruction() + + val clone = cloneType + val cloneFields = getRecursiveFields(clone, "(vec root)").toMap + + // Create the Vec literal binding from litArgs of arguments + val vecLitLinkedMap = new mutable.LinkedHashMap[Data, LitArg]() + elementInitializers.sortBy { case (a, _) => a }.foreach { case (fieldIndex, value) => + val field = clone.apply(fieldIndex) + val fieldName = cloneFields.getOrElse(field, + throw new VecLiteralException(s"field $field (with value $value) is not a field," + + s" ensure the field is specified as a function returning a field on an object of class ${this.getClass}," + + s" eg '_.a' to select hypothetical bundle field 'a'") + ) + + val valueBinding = value.topBindingOpt match { + case Some(litBinding: LitBinding) => litBinding + case _ => throw new VecLiteralException(s"field $fieldIndex specified with non-literal value $value") + } + + field match { // Get the litArg(s) for this field + case bitField: Bits => + if (!field.typeEquivalent(bitField)) { + throw new VecLiteralException( + s"VecLit: Literal specified at index $fieldIndex ($value) does not match Vec type $sample_element" + ) + } + if (bitField.getWidth > field.getWidth) { + throw new VecLiteralException( + s"VecLit: Literal specified at index $fieldIndex ($value) is too wide for Vec type $sample_element" + ) + } + val litArg = valueBinding match { + case ElementLitBinding(litArg) => litArg + case BundleLitBinding(litMap) => litMap.getOrElse(value, + throw new BundleLiteralException(s"Field $fieldName specified with unspecified value") + ) + case VecLitBinding(litMap) => litMap.getOrElse(value, + throw new VecLiteralException(s"Field $fieldIndex specified with unspecified value")) + } + val adjustedLitArg = litArg.cloneWithWidth(sample_element.width) + vecLitLinkedMap(bitField) = adjustedLitArg + + case recordField: Record => + if (!(recordField.typeEquivalent(value))) { + throw new VecLiteralException(s"field $fieldIndex $recordField specified with non-type-equivalent value $value") + } + // Copy the source BundleLitBinding with fields (keys) remapped to the clone + val remap = getMatchedFields(value, recordField).toMap + valueBinding.asInstanceOf[BundleLitBinding].litMap.map { case (valueField, valueValue) => + vecLitLinkedMap(remap(valueField)) = valueValue + } + + case vecField: Vec[_] => + if (!(vecField typeEquivalent value)) { + throw new VecLiteralException(s"field $fieldIndex $vecField specified with non-type-equivalent value $value") + } + // Copy the source VecLitBinding with vecFields (keys) remapped to the clone + val remap = getMatchedFields(value, vecField).toMap + value.topBinding.asInstanceOf[VecLitBinding].litMap.map { case (valueField, valueValue) => + vecLitLinkedMap(remap(valueField)) = valueValue + } + + case enumField: EnumType => { + if (!(enumField typeEquivalent value)) { + throw new VecLiteralException(s"field $fieldIndex $enumField specified with non-type-equivalent enum value $value") + } + val litArg = valueBinding match { + case ElementLitBinding(litArg) => litArg + case _ => + throw new VecLiteralException(s"field $fieldIndex $enumField could not bematched with $valueBinding") + } + vecLitLinkedMap(field) = litArg + } + + case _ => throw new VecLiteralException(s"unsupported field $fieldIndex of type $field") + } + } + + clone.bind(VecLitBinding(ListMap(vecLitLinkedMap.toSeq:_*))) + clone + } } object VecInit extends SourceInfoDoc { @@ -528,25 +729,6 @@ abstract class Record(private[chisel3] implicit val compileOptions: CompileOptio * }}} */ private[chisel3] def _makeLit(elems: (this.type => (Data, Data))*): this.type = { - // Returns pairs of all fields, element-level and containers, in a Record and their path names - def getRecursiveFields(data: Data, path: String): Seq[(Data, String)] = data match { - case data: Record => data.elements.map { case (fieldName, fieldData) => - getRecursiveFields(fieldData, s"$path.$fieldName") - }.fold(Seq(data -> path)) { _ ++ _ } - case data => Seq(data -> path) // we don't support or recurse into other Aggregate types here - } - - // Returns pairs of corresponding fields between two Records of the same type - def getMatchedFields(x: Data, y: Data): Seq[(Data, Data)] = (x, y) match { - case (x: Element, y: Element) => - require(x typeEquivalent y) - Seq(x -> y) - case (x: Record, y: Record) => - (x.elements zip y.elements).map { case ((xName, xElt), (yName, yElt)) => - require(xName == yName) // assume fields returned in same, deterministic order - getMatchedFields(xElt, yElt) - }.fold(Seq(x -> y)) { _ ++ _ } - } requireIsChiselType(this, "bundle literal constructor model") val clone = cloneType @@ -572,9 +754,15 @@ abstract class Record(private[chisel3] implicit val compileOptions: CompileOptio val litArg = valueBinding match { case ElementLitBinding(litArg) => litArg case BundleLitBinding(litMap) => litMap.getOrElse(value, - throw new BundleLiteralException(s"Field $fieldName specified with unspecified value")) + throw new BundleLiteralException(s"Field $fieldName specified with unspecified value") + ) + case VecLitBinding(litMap) => litMap.getOrElse(value, + throw new VecLiteralException(s"Vec literal $fieldName specified with out literal values") + ) + } Seq(field -> litArg) + case field: Record => if (!(field typeEquivalent value)) { throw new BundleLiteralException(s"field $fieldName $field specified with non-type-equivalent value $value") @@ -584,18 +772,33 @@ abstract class Record(private[chisel3] implicit val compileOptions: CompileOptio value.topBinding.asInstanceOf[BundleLitBinding].litMap.map { case (valueField, valueValue) => remap(valueField) -> valueValue } + + case vecField: Vec[_] => + if (!(vecField typeEquivalent value)) { + throw new BundleLiteralException(s"field $fieldName $vecField specified with non-type-equivalent value $value") + } + // Copy the source BundleLitBinding with fields (keys) remapped to the clone + val remap = getMatchedFields(value, vecField).toMap + value.topBinding.asInstanceOf[VecLitBinding].litMap.map { case (valueField, valueValue) => + remap(valueField) -> valueValue + } + case field: EnumType => { if (!(field typeEquivalent value)) { throw new BundleLiteralException(s"field $fieldName $field specified with non-type-equivalent enum value $value") } val litArg = valueBinding match { case ElementLitBinding(litArg) => litArg + case _ => + throw new BundleLiteralException(s"field $fieldName $field could not be matched with $valueBinding") } Seq(field -> litArg) } case _ => throw new BundleLiteralException(s"unsupported field $fieldName of type $field") } - } // don't convert to a Map yet to preserve duplicate keys + } + + // don't convert to a Map yet to preserve duplicate keys val duplicates = bundleLitMap.map(_._1).groupBy(identity).collect { case (x, elts) if elts.size > 1 => x } if (!duplicates.isEmpty) { val duplicateNames = duplicates.map(cloneFields(_)).mkString(", ") @@ -694,6 +897,7 @@ class AutoClonetypeException(message: String) extends ChiselException(message) package experimental { class BundleLiteralException(message: String) extends ChiselException(message) + class VecLiteralException(message: String) extends ChiselException(message) } diff --git a/core/src/main/scala/chisel3/Data.scala b/core/src/main/scala/chisel3/Data.scala index 377a94e6..0241f248 100644 --- a/core/src/main/scala/chisel3/Data.scala +++ b/core/src/main/scala/chisel3/Data.scala @@ -392,6 +392,7 @@ abstract class Data extends HasId with NamedComponent with SourceInfoDoc { case Some(DontCareBinding()) => s"(DontCare)" case Some(ElementLitBinding(litArg)) => s"(unhandled literal)" case Some(BundleLitBinding(litMap)) => s"(unhandled bundle literal)" + case Some(VecLitBinding(litMap)) => s"(unhandled vec literal)" }).getOrElse("") // Return ALL elements at root of this type. @@ -491,6 +492,11 @@ abstract class Data extends HasId with NamedComponent with SourceInfoDoc { case Some(litArg) => litArg case _ => materializeWire() // FIXME FIRRTL doesn't have Bundle literal expressions } + case Some(VecLitBinding(litMap)) => + litMap.get(this) match { + case Some(litArg) => litArg + case _ => materializeWire() // FIXME FIRRTL doesn't have Vec literal expressions + } case Some(DontCareBinding()) => materializeWire() // FIXME FIRRTL doesn't have a DontCare expression so materialize a Wire // Non-literals diff --git a/core/src/main/scala/chisel3/Element.scala b/core/src/main/scala/chisel3/Element.scala index 0c99ff70..40291b12 100644 --- a/core/src/main/scala/chisel3/Element.scala +++ b/core/src/main/scala/chisel3/Element.scala @@ -30,6 +30,10 @@ abstract class Element extends Data { case Some(litArg) => Some(ElementLitBinding(litArg)) case _ => Some(DontCareBinding()) } + case Some(VecLitBinding(litMap)) => litMap.get(this) match { + case Some(litArg) => Some(ElementLitBinding(litArg)) + case _ => Some(DontCareBinding()) + } case topBindingOpt => topBindingOpt } diff --git a/core/src/main/scala/chisel3/experimental/package.scala b/core/src/main/scala/chisel3/experimental/package.scala index 4dc7ba4b..e8360430 100644 --- a/core/src/main/scala/chisel3/experimental/package.scala +++ b/core/src/main/scala/chisel3/experimental/package.scala @@ -2,6 +2,8 @@ package chisel3 +import chisel3.internal.sourceinfo.SourceInfo + /** Package for experimental features, which may have their API changed, be removed, etc. * * Because its contents won't necessarily have the same level of stability and support as @@ -124,10 +126,39 @@ package object experimental { object BundleLiterals { implicit class AddBundleLiteralConstructor[T <: Record](x: T) { - def Lit(elems: (T => (Data, Data))*): T = { + def Lit(elems: (T => (Data, Data))*)(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): T = { + x._makeLit(elems: _*) + } + } + } + + /** This class provides the `Lit` method needed to define a `Vec` literal + */ + object VecLiterals { + implicit class AddVecLiteralConstructor[T <: Data](x: Vec[T]) { + /** Given a generator of a list tuples of the form [Int, Data] + * constructs a Vec literal, parallel concept to `BundleLiteral` + * + * @param elems tuples of an index and a literal value + * @return + */ + def Lit(elems: (Int, T)*)(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Vec[T] = { x._makeLit(elems: _*) } } + + implicit class AddObjectLiteralConstructor(x: Vec.type) { + /** This provides an literal construction method for cases using + * object `Vec` as in `Vec.Lit(1.U, 2.U)` + */ + def Lit[T <: Data](elems: T*)(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Vec[T] = { + require(elems.nonEmpty, s"Lit.Vec(...) must have at least one element") + val indexElements = elems.zipWithIndex.map { case (element, index) => (index, element)} + val widestElement = elems.maxBy(_.getWidth) + val vec: Vec[T] = Vec.apply(indexElements.length, chiselTypeOf(widestElement)) + vec.Lit(indexElements:_*) + } + } } // Use to add a prefix to any component generated in input scope diff --git a/core/src/main/scala/chisel3/internal/Binding.scala b/core/src/main/scala/chisel3/internal/Binding.scala index 9e17aded..8a3c4330 100644 --- a/core/src/main/scala/chisel3/internal/Binding.scala +++ b/core/src/main/scala/chisel3/internal/Binding.scala @@ -6,6 +6,8 @@ import chisel3._ import chisel3.experimental.BaseModule import chisel3.internal.firrtl.LitArg +import scala.collection.immutable.ListMap + /** Requires that a node is hardware ("bound") */ object requireIsHardware { @@ -123,3 +125,5 @@ sealed trait LitBinding extends UnconstrainedBinding with ReadOnlyBinding case class ElementLitBinding(litArg: LitArg) extends LitBinding // Literal binding attached to the root of a Bundle, containing literal values of its children. case class BundleLitBinding(litMap: Map[Data, LitArg]) extends LitBinding +// Literal binding attached to the root of a Vec, containing literal values of its children. +case class VecLitBinding(litMap: ListMap[Data, LitArg]) extends LitBinding diff --git a/core/src/main/scala/chisel3/internal/firrtl/IR.scala b/core/src/main/scala/chisel3/internal/firrtl/IR.scala index 61f97ce6..81b4f7ab 100644 --- a/core/src/main/scala/chisel3/internal/firrtl/IR.scala +++ b/core/src/main/scala/chisel3/internal/firrtl/IR.scala @@ -91,6 +91,14 @@ abstract class LitArg(val num: BigInt, widthArg: Width) extends Arg { elem } + /** Provides a mechanism that LitArgs can have their width adjusted + * to match other members of a VecLiteral + * + * @param newWidth the new width for this + * @return + */ + def cloneWithWidth(newWidth: Width): this.type + protected def minWidth: Int if (forcedWidth) { require(widthArg.get >= minWidth, @@ -106,6 +114,10 @@ case class ULit(n: BigInt, w: Width) extends LitArg(n, w) { def name: String = "UInt" + width + "(\"h0" + num.toString(16) + "\")" def minWidth: Int = 1 max n.bitLength + def cloneWithWidth(newWidth: Width): this.type = { + ULit(n, newWidth).asInstanceOf[this.type] + } + require(n >= 0, s"UInt literal ${n} is negative") } @@ -115,6 +127,10 @@ case class SLit(n: BigInt, w: Width) extends LitArg(n, w) { s"asSInt(${ULit(unsigned, width).name})" } def minWidth: Int = 1 + n.bitLength + + def cloneWithWidth(newWidth: Width): this.type = { + SLit(n, newWidth).asInstanceOf[this.type] + } } case class FPLit(n: BigInt, w: Width, binaryPoint: BinaryPoint) extends LitArg(n, w) { @@ -123,6 +139,10 @@ case class FPLit(n: BigInt, w: Width, binaryPoint: BinaryPoint) extends LitArg(n s"asFixedPoint(${ULit(unsigned, width).name}, ${binaryPoint.asInstanceOf[KnownBinaryPoint].value})" } def minWidth: Int = 1 + n.bitLength + + def cloneWithWidth(newWidth: Width): this.type = { + FPLit(n, newWidth, binaryPoint).asInstanceOf[this.type] + } } case class IntervalLit(n: BigInt, w: Width, binaryPoint: BinaryPoint) extends LitArg(n, w) { @@ -135,6 +155,10 @@ case class IntervalLit(n: BigInt, w: Width, binaryPoint: BinaryPoint) extends Li IntervalRange.getBound(isClosed = true, BigDecimal(n)), IntervalRange.getRangeWidth(binaryPoint)) } def minWidth: Int = 1 + n.bitLength + + def cloneWithWidth(newWidth: Width): this.type = { + IntervalLit(n, newWidth, binaryPoint).asInstanceOf[this.type] + } } case class Ref(name: String) extends Arg -- cgit v1.2.3 From 4d8fed00225d15221cf32177ea9147b20d0b91f7 Mon Sep 17 00:00:00 2001 From: Kevin Laeufer Date: Thu, 29 Apr 2021 11:52:20 -0700 Subject: verification: guard statements with module reset (#1891) --- .../experimental/verification/package.scala | 24 ++++++++++++---------- 1 file changed, 13 insertions(+), 11 deletions(-) (limited to 'core/src') diff --git a/core/src/main/scala/chisel3/experimental/verification/package.scala b/core/src/main/scala/chisel3/experimental/verification/package.scala index 5c71bd5f..816299a3 100644 --- a/core/src/main/scala/chisel3/experimental/verification/package.scala +++ b/core/src/main/scala/chisel3/experimental/verification/package.scala @@ -2,9 +2,8 @@ package chisel3.experimental -import chisel3.{Bool, CompileOptions} +import chisel3._ import chisel3.internal.Builder -import chisel3.internal.Builder.pushCommand import chisel3.internal.firrtl.{Formal, Verification} import chisel3.internal.sourceinfo.SourceInfo @@ -13,9 +12,10 @@ package object verification { def apply(predicate: Bool, msg: String = "")( implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Unit = { - val clock = Builder.forcedClock - pushCommand(Verification(Formal.Assert, sourceInfo, clock.ref, - predicate.ref, msg)) + when (!Module.reset.asBool) { + val clock = Module.clock + Builder.pushCommand(Verification(Formal.Assert, sourceInfo, clock.ref, predicate.ref, msg)) + } } } @@ -23,9 +23,10 @@ package object verification { def apply(predicate: Bool, msg: String = "")( implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Unit = { - val clock = Builder.forcedClock - pushCommand(Verification(Formal.Assume, sourceInfo, clock.ref, - predicate.ref, msg)) + when (!Module.reset.asBool) { + val clock = Module.clock + Builder.pushCommand(Verification(Formal.Assume, sourceInfo, clock.ref, predicate.ref, msg)) + } } } @@ -33,9 +34,10 @@ package object verification { def apply(predicate: Bool, msg: String = "")( implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Unit = { - val clock = Builder.forcedClock - pushCommand(Verification(Formal.Cover, sourceInfo, clock.ref, - predicate.ref, msg)) + val clock = Module.clock + when (!Module.reset.asBool) { + Builder.pushCommand(Verification(Formal.Cover, sourceInfo, clock.ref, predicate.ref, msg)) + } } } } -- cgit v1.2.3 From c5861176887bfa529277e686df09a42aeceb6cd7 Mon Sep 17 00:00:00 2001 From: Jack Koenig Date: Thu, 29 Apr 2021 16:18:06 -0700 Subject: Scala 2.13 support (#1751) --- .../scala/collection/immutable/package.scala | 13 +++++++ core/src/main/scala/chisel3/Aggregate.scala | 12 +++--- core/src/main/scala/chisel3/Bits.scala | 1 + core/src/main/scala/chisel3/Data.scala | 45 +++++++++++----------- core/src/main/scala/chisel3/Module.scala | 4 +- core/src/main/scala/chisel3/Num.scala | 2 +- core/src/main/scala/chisel3/RawModule.scala | 1 - core/src/main/scala/chisel3/internal/Binding.scala | 4 +- core/src/main/scala/chisel3/internal/Builder.scala | 2 +- core/src/main/scala/chisel3/internal/Error.scala | 6 +-- core/src/main/scala/chisel3/internal/Namer.scala | 14 +++++-- core/src/main/scala/chisel3/package.scala | 3 -- 12 files changed, 61 insertions(+), 46 deletions(-) create mode 100644 core/src/main/scala-2.12/scala/collection/immutable/package.scala (limited to 'core/src') diff --git a/core/src/main/scala-2.12/scala/collection/immutable/package.scala b/core/src/main/scala-2.12/scala/collection/immutable/package.scala new file mode 100644 index 00000000..7ae87d9b --- /dev/null +++ b/core/src/main/scala-2.12/scala/collection/immutable/package.scala @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: Apache-2.0 + +package scala.collection + +import scala.collection.immutable.ListMap + +package object immutable { + val SeqMap = ListMap + type SeqMap[K, +V] = ListMap[K, V] + + val VectorMap = ListMap + type VectorMap[K, +V] = ListMap[K, V] +} diff --git a/core/src/main/scala/chisel3/Aggregate.scala b/core/src/main/scala/chisel3/Aggregate.scala index c0b965b6..0031e53b 100644 --- a/core/src/main/scala/chisel3/Aggregate.scala +++ b/core/src/main/scala/chisel3/Aggregate.scala @@ -4,7 +4,7 @@ package chisel3 import chisel3.experimental.VecLiterals.AddVecLiteralConstructor -import scala.collection.immutable.ListMap +import scala.collection.immutable.{SeqMap, VectorMap} import scala.collection.mutable.{HashSet, LinkedHashMap} import scala.language.experimental.macros import chisel3.experimental.{BaseModule, BundleLiteralException, ChiselEnum, EnumType, VecLiteralException} @@ -516,7 +516,7 @@ sealed class Vec[T <: Data] private[chisel3] (gen: => T, val length: Int) } } - clone.bind(VecLitBinding(ListMap(vecLitLinkedMap.toSeq:_*))) + clone.bind(VecLitBinding(VectorMap(vecLitLinkedMap.toSeq:_*))) clone } } @@ -595,7 +595,7 @@ object VecInit extends SourceInfoDoc { /** A trait for [[Vec]]s containing common hardware generators for collection * operations. */ -trait VecLike[T <: Data] extends collection.IndexedSeq[T] with HasId with SourceInfoDoc { +trait VecLike[T <: Data] extends IndexedSeq[T] with HasId with SourceInfoDoc { def apply(p: UInt): T = macro CompileOptionsTransform.pArg /** @group SourceInfoTransformMacro */ @@ -835,7 +835,7 @@ abstract class Record(private[chisel3] implicit val compileOptions: CompileOptio s"$className$bindingString" } - val elements: ListMap[String, Data] + def elements: SeqMap[String, Data] /** Name for Pretty Printing */ def className: String = this.getClass.getSimpleName @@ -958,7 +958,7 @@ abstract class Bundle(implicit compileOptions: CompileOptions) extends Record { * assert(uint === "h12345678".U) // This will pass * }}} */ - final lazy val elements: ListMap[String, Data] = { + final lazy val elements: SeqMap[String, Data] = { val nameMap = LinkedHashMap[String, Data]() for (m <- getPublicFields(classOf[Bundle])) { getBundleField(m) match { @@ -985,7 +985,7 @@ abstract class Bundle(implicit compileOptions: CompileOptions) extends Record { } } } - ListMap(nameMap.toSeq sortWith { case ((an, a), (bn, b)) => (a._id > b._id) || ((a eq b) && (an > bn)) }: _*) + VectorMap(nameMap.toSeq sortWith { case ((an, a), (bn, b)) => (a._id > b._id) || ((a eq b) && (an > bn)) }: _*) } /** diff --git a/core/src/main/scala/chisel3/Bits.scala b/core/src/main/scala/chisel3/Bits.scala index 17829143..aa5b1abb 100644 --- a/core/src/main/scala/chisel3/Bits.scala +++ b/core/src/main/scala/chisel3/Bits.scala @@ -1147,6 +1147,7 @@ sealed class Bool() extends UInt(1.W) with Reset { package experimental { import chisel3.internal.firrtl.BinaryPoint + import chisel3.internal.requireIsHardware // Fix ambiguous import /** Chisel types that have binary points support retrieving * literal values as `Double` or `BigDecimal` diff --git a/core/src/main/scala/chisel3/Data.scala b/core/src/main/scala/chisel3/Data.scala index 0241f248..0832161e 100644 --- a/core/src/main/scala/chisel3/Data.scala +++ b/core/src/main/scala/chisel3/Data.scala @@ -122,6 +122,7 @@ object ActualDirection { } package experimental { + import chisel3.internal.requireIsHardware // Fix ambiguous import /** Experimental hardware construction reflection API */ @@ -763,35 +764,33 @@ object WireDefault { } } -package internal { - /** RHS (source) for Invalidate API. - * Causes connection logic to emit a DefInvalid when connected to an output port (or wire). - */ - private[chisel3] object InternalDontCare extends Element { - // This object should be initialized before we execute any user code that refers to it, - // otherwise this "Chisel" object will end up on the UserModule's id list. - // We make it private to chisel3 so it has to be accessed through the package object. +/** RHS (source) for Invalidate API. + * Causes connection logic to emit a DefInvalid when connected to an output port (or wire). + */ +final case object DontCare extends Element { + // This object should be initialized before we execute any user code that refers to it, + // otherwise this "Chisel" object will end up on the UserModule's id list. + // We make it private to chisel3 so it has to be accessed through the package object. - private[chisel3] override val width: Width = UnknownWidth() + private[chisel3] override val width: Width = UnknownWidth() - bind(DontCareBinding(), SpecifiedDirection.Output) - override def cloneType: this.type = DontCare + bind(DontCareBinding(), SpecifiedDirection.Output) + override def cloneType: this.type = DontCare - override def toString: String = "DontCare()" + override def toString: String = "DontCare()" - override def litOption: Option[BigInt] = None + override def litOption: Option[BigInt] = None - def toPrintable: Printable = PString("DONTCARE") + def toPrintable: Printable = PString("DONTCARE") - private[chisel3] def connectFromBits(that: Bits)(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Unit = { - Builder.error("connectFromBits: DontCare cannot be a connection sink (LHS)") - } + private[chisel3] def connectFromBits(that: Bits)(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Unit = { + Builder.error("connectFromBits: DontCare cannot be a connection sink (LHS)") + } - def do_asUInt(implicit sourceInfo: chisel3.internal.sourceinfo.SourceInfo, compileOptions: CompileOptions): UInt = { - Builder.error("DontCare does not have a UInt representation") - 0.U - } - // DontCare's only match themselves. - private[chisel3] def typeEquivalent(that: Data): Boolean = that == DontCare + def do_asUInt(implicit sourceInfo: chisel3.internal.sourceinfo.SourceInfo, compileOptions: CompileOptions): UInt = { + Builder.error("DontCare does not have a UInt representation") + 0.U } + // DontCare's only match themselves. + private[chisel3] def typeEquivalent(that: Data): Boolean = that == DontCare } diff --git a/core/src/main/scala/chisel3/Module.scala b/core/src/main/scala/chisel3/Module.scala index ede9ccc6..b204be8d 100644 --- a/core/src/main/scala/chisel3/Module.scala +++ b/core/src/main/scala/chisel3/Module.scala @@ -4,9 +4,7 @@ package chisel3 import scala.collection.immutable.ListMap import scala.collection.mutable.{ArrayBuffer, HashMap} -import scala.collection.JavaConversions._ import scala.language.experimental.macros -import java.util.IdentityHashMap import chisel3.internal._ import chisel3.internal.Builder._ @@ -139,6 +137,8 @@ abstract class Module(implicit moduleCompileOptions: CompileOptions) extends Raw package experimental { + import chisel3.internal.requireIsChiselType // Fix ambiguous import + object IO { /** Constructs a port for the current Module * diff --git a/core/src/main/scala/chisel3/Num.scala b/core/src/main/scala/chisel3/Num.scala index e1af9bdb..70f2fbf0 100644 --- a/core/src/main/scala/chisel3/Num.scala +++ b/core/src/main/scala/chisel3/Num.scala @@ -226,7 +226,7 @@ trait NumObject { */ def toBigInt(x: BigDecimal, binaryPoint: Int): BigInt = { val multiplier = math.pow(2, binaryPoint) - val result = (x * multiplier).rounded.toBigInt() + val result = (x * multiplier).rounded.toBigInt result } diff --git a/core/src/main/scala/chisel3/RawModule.scala b/core/src/main/scala/chisel3/RawModule.scala index d2ba6e84..f678c587 100644 --- a/core/src/main/scala/chisel3/RawModule.scala +++ b/core/src/main/scala/chisel3/RawModule.scala @@ -4,7 +4,6 @@ package chisel3 import scala.collection.mutable.{ArrayBuffer, HashMap} import scala.util.Try -import scala.collection.JavaConversions._ import scala.language.experimental.macros import chisel3.experimental.BaseModule diff --git a/core/src/main/scala/chisel3/internal/Binding.scala b/core/src/main/scala/chisel3/internal/Binding.scala index 8a3c4330..300803ce 100644 --- a/core/src/main/scala/chisel3/internal/Binding.scala +++ b/core/src/main/scala/chisel3/internal/Binding.scala @@ -6,7 +6,7 @@ import chisel3._ import chisel3.experimental.BaseModule import chisel3.internal.firrtl.LitArg -import scala.collection.immutable.ListMap +import scala.collection.immutable.VectorMap /** Requires that a node is hardware ("bound") */ @@ -126,4 +126,4 @@ case class ElementLitBinding(litArg: LitArg) extends LitBinding // Literal binding attached to the root of a Bundle, containing literal values of its children. case class BundleLitBinding(litMap: Map[Data, LitArg]) extends LitBinding // Literal binding attached to the root of a Vec, containing literal values of its children. -case class VecLitBinding(litMap: ListMap[Data, LitArg]) extends LitBinding +case class VecLitBinding(litMap: VectorMap[Data, LitArg]) extends LitBinding diff --git a/core/src/main/scala/chisel3/internal/Builder.scala b/core/src/main/scala/chisel3/internal/Builder.scala index 084bdc88..e1e4d460 100644 --- a/core/src/main/scala/chisel3/internal/Builder.scala +++ b/core/src/main/scala/chisel3/internal/Builder.scala @@ -655,7 +655,7 @@ private[chisel3] object Builder extends LazyLogging { errors.checkpoint() logger.warn("Done elaborating.") - (Circuit(components.last.name, components, annotations), mod) + (Circuit(components.last.name, components.toSeq, annotations.toSeq), mod) } } initializeSingletons() diff --git a/core/src/main/scala/chisel3/internal/Error.scala b/core/src/main/scala/chisel3/internal/Error.scala index 134f4c87..454be360 100644 --- a/core/src/main/scala/chisel3/internal/Error.scala +++ b/core/src/main/scala/chisel3/internal/Error.scala @@ -45,7 +45,7 @@ object ExceptionHelpers { } // Step 1: Remove elements from the top in the package trimlist - ((a: Array[StackTraceElement]) => a.view.dropWhile(inTrimlist)) + ((a: Array[StackTraceElement]) => a.dropWhile(inTrimlist)) // Step 2: Optionally remove elements from the bottom until the anchor .andThen(_.reverse) .andThen( a => @@ -125,10 +125,10 @@ class ChiselException(message: String, cause: Throwable = null) extends Exceptio } val trimmedLeft = throwable.getStackTrace().view.dropWhile(isBlacklisted) - val trimmedReverse = trimmedLeft.reverse + val trimmedReverse = trimmedLeft.toIndexedSeq.reverse.view .dropWhile(ste => !ste.getClassName.startsWith(builderName)) .dropWhile(isBlacklisted) - trimmedReverse.reverse.toArray + trimmedReverse.toIndexedSeq.reverse.toArray } def chiselStackTrace: String = { diff --git a/core/src/main/scala/chisel3/internal/Namer.scala b/core/src/main/scala/chisel3/internal/Namer.scala index 1694d71d..c6e36cb6 100644 --- a/core/src/main/scala/chisel3/internal/Namer.scala +++ b/core/src/main/scala/chisel3/internal/Namer.scala @@ -8,9 +8,8 @@ import chisel3.experimental.NoChiselNamePrefix import scala.collection.mutable.Stack import scala.collection.mutable.ListBuffer -import scala.collection.JavaConversions._ - import java.util.IdentityHashMap +import scala.collection.JavaConverters._ /** Recursive Function Namer overview * @@ -81,7 +80,14 @@ class NamingContext extends NamingContextInterface { def addDescendant(ref: Any, descendant: NamingContext) { ref match { case ref: AnyRef => - descendants.getOrElseUpdate(ref, ListBuffer[NamingContext]()) += descendant + // getOrElseUpdate + val l = descendants.get(ref) + val buf = if (l != null) l else { + val value = ListBuffer[NamingContext]() + descendants.put(ref, value) + value + } + buf += descendant case _ => anonymousDescendants += descendant } } @@ -111,7 +117,7 @@ class NamingContext extends NamingContextInterface { } } - for (descendant <- descendants.values().flatten) { + for (descendant <- descendants.values.asScala.flatten) { // Where we have a broken naming link, just ignore the missing parts descendant.namePrefix(prefix) } diff --git a/core/src/main/scala/chisel3/package.scala b/core/src/main/scala/chisel3/package.scala index d5a4bfae..64cfa8b9 100644 --- a/core/src/main/scala/chisel3/package.scala +++ b/core/src/main/scala/chisel3/package.scala @@ -207,9 +207,6 @@ package object chisel3 { a.allElements } def getModulePorts(m: Module): Seq[Port] = m.getPorts - // Invalidate API - a DontCare element for explicit assignment to outputs, - // indicating the signal is intentionally not driven. - val DontCare = chisel3.internal.InternalDontCare class BindingException(message: String) extends ChiselException(message) /** A function expected a Chisel type but got a hardware object -- cgit v1.2.3 From f8053db3d20b733e0119b77595f0cdfcdab71057 Mon Sep 17 00:00:00 2001 From: Deborah Soung Date: Thu, 24 Jun 2021 14:03:28 -0700 Subject: create and extend annotatable BaseSim class for verification nodes (#1968) * prototype annotating verif constructs * switch to final class * name emissions * moving BaseSim to experimental * adding name tests * fixing quotation escapes * emitting names, but everything has a default name * only name things with provided/suggested names * name every BaseSim node * removing msg, unused imports * fixing file exist calls--- core/src/main/scala/chisel3/RawModule.scala | 4 ++-- .../main/scala/chisel3/experimental/package.scala | 6 +++++ .../experimental/verification/package.scala | 28 +++++++++++++++++----- .../scala/chisel3/internal/firrtl/Converter.scala | 4 ++-- .../main/scala/chisel3/internal/firrtl/IR.scala | 5 ++-- 5 files changed, 34 insertions(+), 13 deletions(-) (limited to 'core/src') diff --git a/core/src/main/scala/chisel3/RawModule.scala b/core/src/main/scala/chisel3/RawModule.scala index f678c587..de93e781 100644 --- a/core/src/main/scala/chisel3/RawModule.scala +++ b/core/src/main/scala/chisel3/RawModule.scala @@ -5,8 +5,7 @@ package chisel3 import scala.collection.mutable.{ArrayBuffer, HashMap} import scala.util.Try import scala.language.experimental.macros - -import chisel3.experimental.BaseModule +import chisel3.experimental.{BaseModule, BaseSim} import chisel3.internal._ import chisel3.internal.Builder._ import chisel3.internal.firrtl._ @@ -77,6 +76,7 @@ abstract class RawModule(implicit moduleCompileOptions: CompileOptions) id match { case id: BaseModule => id.forceName(None, default=id.desiredName, _namespace) case id: MemBase[_] => id.forceName(None, default="MEM", _namespace) + case id: BaseSim => id.forceName(None, default="SIM", _namespace) case id: Data => if (id.isSynthesizable) { id.topBinding match { diff --git a/core/src/main/scala/chisel3/experimental/package.scala b/core/src/main/scala/chisel3/experimental/package.scala index e8360430..8018159f 100644 --- a/core/src/main/scala/chisel3/experimental/package.scala +++ b/core/src/main/scala/chisel3/experimental/package.scala @@ -2,6 +2,7 @@ package chisel3 +import chisel3.internal.NamedComponent import chisel3.internal.sourceinfo.SourceInfo /** Package for experimental features, which may have their API changed, be removed, etc. @@ -165,4 +166,9 @@ package object experimental { val prefix = chisel3.internal.prefix // Use to remove prefixes not in provided scope val noPrefix = chisel3.internal.noPrefix + + /** Base simulation-only component. */ + abstract class BaseSim extends NamedComponent { + _parent.foreach(_.addId(this)) + } } diff --git a/core/src/main/scala/chisel3/experimental/verification/package.scala b/core/src/main/scala/chisel3/experimental/verification/package.scala index 816299a3..ca15a5c4 100644 --- a/core/src/main/scala/chisel3/experimental/verification/package.scala +++ b/core/src/main/scala/chisel3/experimental/verification/package.scala @@ -8,36 +8,52 @@ import chisel3.internal.firrtl.{Formal, Verification} import chisel3.internal.sourceinfo.SourceInfo package object verification { + + /** Named class for assertions. */ + final class Assert(val predicate: Bool) extends BaseSim + + /** Named class for assumes. */ + final class Assume(val predicate: Bool) extends BaseSim + + /** Named class for covers. */ + final class Cover(val predicate: Bool) extends BaseSim + object assert { def apply(predicate: Bool, msg: String = "")( implicit sourceInfo: SourceInfo, - compileOptions: CompileOptions): Unit = { + compileOptions: CompileOptions): Assert = { + val a = new Assert(predicate) when (!Module.reset.asBool) { val clock = Module.clock - Builder.pushCommand(Verification(Formal.Assert, sourceInfo, clock.ref, predicate.ref, msg)) + Builder.pushCommand(Verification(a, Formal.Assert, sourceInfo, clock.ref, predicate.ref, msg)) } + a } } object assume { def apply(predicate: Bool, msg: String = "")( implicit sourceInfo: SourceInfo, - compileOptions: CompileOptions): Unit = { + compileOptions: CompileOptions): Assume = { + val a = new Assume(predicate) when (!Module.reset.asBool) { val clock = Module.clock - Builder.pushCommand(Verification(Formal.Assume, sourceInfo, clock.ref, predicate.ref, msg)) + Builder.pushCommand(Verification(a, Formal.Assume, sourceInfo, clock.ref, predicate.ref, msg)) } + a } } object cover { def apply(predicate: Bool, msg: String = "")( implicit sourceInfo: SourceInfo, - compileOptions: CompileOptions): Unit = { + compileOptions: CompileOptions): Cover = { val clock = Module.clock + val c = new Cover(predicate) when (!Module.reset.asBool) { - Builder.pushCommand(Verification(Formal.Cover, sourceInfo, clock.ref, predicate.ref, msg)) + Builder.pushCommand(Verification(c, Formal.Cover, sourceInfo, clock.ref, predicate.ref, msg)) } + c } } } diff --git a/core/src/main/scala/chisel3/internal/firrtl/Converter.scala b/core/src/main/scala/chisel3/internal/firrtl/Converter.scala index ff0fa770..40d3691c 100644 --- a/core/src/main/scala/chisel3/internal/firrtl/Converter.scala +++ b/core/src/main/scala/chisel3/internal/firrtl/Converter.scala @@ -136,14 +136,14 @@ private[chisel3] object Converter { val (fmt, args) = unpack(pable, ctx) Some(fir.Print(convert(info), fir.StringLit(fmt), args.map(a => convert(a, ctx, info)), convert(clock, ctx, info), firrtl.Utils.one)) - case Verification(op, info, clk, pred, msg) => + case e @ Verification(_, op, info, clk, pred, msg) => val firOp = op match { case Formal.Assert => fir.Formal.Assert case Formal.Assume => fir.Formal.Assume case Formal.Cover => fir.Formal.Cover } Some(fir.Verification(firOp, convert(info), convert(clk, ctx, info), - convert(pred, ctx, info), firrtl.Utils.one, fir.StringLit(msg))) + convert(pred, ctx, info), firrtl.Utils.one, fir.StringLit(msg), e.name)) case _ => None } diff --git a/core/src/main/scala/chisel3/internal/firrtl/IR.scala b/core/src/main/scala/chisel3/internal/firrtl/IR.scala index 81b4f7ab..5dc72a43 100644 --- a/core/src/main/scala/chisel3/internal/firrtl/IR.scala +++ b/core/src/main/scala/chisel3/internal/firrtl/IR.scala @@ -3,7 +3,6 @@ package chisel3.internal.firrtl import firrtl.{ir => fir} - import chisel3._ import chisel3.internal._ import chisel3.internal.sourceinfo.SourceInfo @@ -765,8 +764,8 @@ object Formal extends Enumeration { val Assume = Value("assume") val Cover = Value("cover") } -case class Verification(op: Formal.Value, sourceInfo: SourceInfo, clock: Arg, - predicate: Arg, message: String) extends Command +case class Verification[T <: BaseSim](id: T, op: Formal.Value, sourceInfo: SourceInfo, clock: Arg, + predicate: Arg, message: String) extends Definition abstract class Component extends Arg { def id: BaseModule def name: String -- cgit v1.2.3 From 71fff0795a07cb6b136d202a3b75adfee42be6fe Mon Sep 17 00:00:00 2001 From: Felix Yan Date: Fri, 25 Jun 2021 23:22:34 +0800 Subject: Correct typos in core/src/main/scala/chisel3/Num.scala (#1976) --- core/src/main/scala/chisel3/Num.scala | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'core/src') diff --git a/core/src/main/scala/chisel3/Num.scala b/core/src/main/scala/chisel3/Num.scala index 70f2fbf0..6dd299f4 100644 --- a/core/src/main/scala/chisel3/Num.scala +++ b/core/src/main/scala/chisel3/Num.scala @@ -156,7 +156,7 @@ trait Num[T <: Data] { /** Minimum operator * * @param that a hardware $coll - * @return a $numType with a value equal to the mimimum value of this $coll and `that` + * @return a $numType with a value equal to the minimum value of this $coll and `that` * $maxWidth * @group Arithmetic */ @@ -169,7 +169,7 @@ trait Num[T <: Data] { /** Maximum operator * * @param that a $numType - * @return a $numType with a value equal to the mimimum value of this $coll and `that` + * @return a $numType with a value equal to the minimum value of this $coll and `that` * $maxWidth * @group Arithmetic */ @@ -304,4 +304,4 @@ trait NumObject { throw new ChiselException(s"Error converting BigDecimal $value to BigInt, binary point must be known, not $x") } } -} \ No newline at end of file +} -- cgit v1.2.3 From d3e13ce24956871d2f0fd01ca3a7d89317e3db68 Mon Sep 17 00:00:00 2001 From: Jack Koenig Date: Wed, 23 Jun 2021 17:11:22 -0700 Subject: Fix CloneModuleAsRecord support for .toTarget --- core/src/main/scala/chisel3/BlackBox.scala | 8 +- core/src/main/scala/chisel3/Module.scala | 91 ++++++++++++++++++---- core/src/main/scala/chisel3/RawModule.scala | 6 +- core/src/main/scala/chisel3/internal/Builder.scala | 2 +- .../scala/chisel3/internal/firrtl/Converter.scala | 19 ++++- .../main/scala/chisel3/internal/firrtl/IR.scala | 13 +++- 6 files changed, 110 insertions(+), 29 deletions(-) (limited to 'core/src') diff --git a/core/src/main/scala/chisel3/BlackBox.scala b/core/src/main/scala/chisel3/BlackBox.scala index 8ba4b612..0c42600f 100644 --- a/core/src/main/scala/chisel3/BlackBox.scala +++ b/core/src/main/scala/chisel3/BlackBox.scala @@ -62,7 +62,7 @@ package experimental { * @note The parameters API is experimental and may change */ abstract class ExtModule(val params: Map[String, Param] = Map.empty[String, Param]) extends BaseBlackBox { - private[chisel3] override def generateComponent(): Component = { + private[chisel3] override def generateComponent(): Option[Component] = { require(!_closed, "Can't generate module more than once") _closed = true @@ -86,7 +86,7 @@ package experimental { val firrtlPorts = getModulePorts map {port => Port(port, port.specifiedDirection)} val component = DefBlackBox(this, name, firrtlPorts, SpecifiedDirection.Unspecified, params) _component = Some(component) - component + _component } private[chisel3] def initializeInParent(parentCompileOptions: CompileOptions): Unit = { @@ -145,7 +145,7 @@ abstract class BlackBox(val params: Map[String, Param] = Map.empty[String, Param // Allow access to bindings from the compatibility package protected def _compatIoPortBound() = portsContains(_io) - private[chisel3] override def generateComponent(): Component = { + private[chisel3] override def generateComponent(): Option[Component] = { _compatAutoWrapPorts() // pre-IO(...) compatibility hack // Restrict IO to just io, clock, and reset @@ -178,7 +178,7 @@ abstract class BlackBox(val params: Map[String, Param] = Map.empty[String, Param val firrtlPorts = namedPorts map {namedPort => Port(namedPort._2, namedPort._2.specifiedDirection)} val component = DefBlackBox(this, name, firrtlPorts, _io.specifiedDirection, params) _component = Some(component) - component + _component } private[chisel3] def initializeInParent(parentCompileOptions: CompileOptions): Unit = { diff --git a/core/src/main/scala/chisel3/Module.scala b/core/src/main/scala/chisel3/Module.scala index b204be8d..77735583 100644 --- a/core/src/main/scala/chisel3/Module.scala +++ b/core/src/main/scala/chisel3/Module.scala @@ -64,13 +64,18 @@ object Module extends SourceInfoDoc { Builder.currentClock = saveClock // Back to clock and reset scope Builder.currentReset = saveReset - val component = module.generateComponent() - Builder.components += component + // Only add the component if the module generates one + val componentOpt = module.generateComponent() + for (component <- componentOpt) { + Builder.components += component + } Builder.setPrefix(savePrefix) // Handle connections at enclosing scope - if(!Builder.currentModule.isEmpty) { + // We use _component because Modules that don't generate them may still have one + if (Builder.currentModule.isDefined && module._component.isDefined) { + val component = module._component.get pushCommand(DefInstance(sourceInfo, module, component.ports)) module.initializeInParent(compileOptions) } @@ -178,20 +183,73 @@ package internal { import chisel3.experimental.BaseModule object BaseModule { - private[chisel3] class ClonePorts (elts: Data*)(implicit compileOptions: CompileOptions) extends Record { + // Private internal class to serve as a _parent for Data in cloned ports + private[chisel3] class ModuleClone(proto: BaseModule) extends BaseModule { + // Don't generate a component, but point to the one for the cloned Module + private[chisel3] def generateComponent(): Option[Component] = { + _component = proto._component + None + } + // This module doesn't acutally exist in the FIRRTL so no initialization to do + private[chisel3] def initializeInParent(parentCompileOptions: CompileOptions): Unit = () + + override def desiredName: String = proto.name + } + + /** Record type returned by CloneModuleAsRecord + * + * @note These are not true Data (the Record doesn't correspond to anything in the emitted + * FIRRTL yet its elements *do*) so have some very specialized behavior. + * @param proto Optional pointer to the Module we are a clone of. Set for first instance, unset + * for clones + */ + private[chisel3] class ClonePorts (proto: Option[BaseModule], elts: Data*)(implicit compileOptions: CompileOptions) extends Record { val elements = ListMap(elts.map(d => d.instanceName -> d.cloneTypeFull): _*) def apply(field: String) = elements(field) - override def cloneType = (new ClonePorts(elts: _*)).asInstanceOf[this.type] + override def cloneType = (new ClonePorts(None, elts: _*)).asInstanceOf[this.type] + + // Because ClonePorts instances are *not* created inside of their parent module, but rather, + // their parent's parent, we have to intercept the standard setRef and replace it with our own + // special Ref type. + // This only applies to ClonePorts created in cloneIORecord, any clones of these Records have + // normal behavior. + // Also, the name of ClonePorts Records needs to be propagated to their parent ModuleClone + // since we have no other way of setting the instance name for those. + private[chisel3] override def setRef(imm: Arg, force: Boolean): Unit = { + val immx = (proto, imm) match { + case (Some(mod), Ref(name)) => + // Our _parent is a ModuleClone that needs its ref to match ours for .toAbsoluteTarget + _parent.foreach(_.setRef(Ref(name), force=true)) + // Return a specialize-ref that will do the right thing + ModuleCloneIO(mod, name) + case _ => imm + } + super.setRef(immx, force) + } + } + + // Recursively set the parent of the start Data and any children (eg. in an Aggregate) + private def setAllParents(start: Data, parent: Option[BaseModule]): Unit = { + def rec(data: Data): Unit = { + data._parent = parent + data match { + case _: Element => + case agg: Aggregate => + agg.getElements.foreach(rec) + } + } + rec(start) } private[chisel3] def cloneIORecord(proto: BaseModule)(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): ClonePorts = { require(proto.isClosed, "Can't clone a module before module close") - val clonePorts = new ClonePorts(proto.getModulePorts: _*) - clonePorts.bind(WireBinding(Builder.forcedUserModule, Builder.currentWhen())) - val cloneInstance = new DefInstance(sourceInfo, proto, proto._component.get.ports) { - override def name = clonePorts.getRef.name - } - pushCommand(cloneInstance) + // We don't create this inside the ModuleClone because we need the ref to be set by the + // currentModule (and not clonePorts) + val clonePorts = new ClonePorts(Some(proto), proto.getModulePorts: _*) + val cloneParent = Module(new ModuleClone(proto)) + clonePorts.bind(PortBinding(cloneParent)) + setAllParents(clonePorts, Some(cloneParent)) + // Normally handled during Module construction but ClonePorts really lives in its parent's parent if (!compileOptions.explicitInvalidate) { pushCommand(DefInvalid(sourceInfo, clonePorts.ref)) } @@ -270,7 +328,7 @@ package experimental { /** Generates the FIRRTL Component (Module or Blackbox) of this Module. * Also closes the module so no more construction can happen inside. */ - private[chisel3] def generateComponent(): Component + private[chisel3] def generateComponent(): Option[Component] /** Sets up this module in the parent context */ @@ -308,9 +366,12 @@ package experimental { /** Legalized name of this module. */ final lazy val name = try { - // If this is a module aspect, it should share the same name as the original module - // Thus, the desired name should be returned without uniquification - if(this.isInstanceOf[ModuleAspect]) desiredName else Builder.globalNamespace.name(desiredName) + // ModuleAspects and ModuleClones are not "true modules" and thus should share + // their original modules names without uniquification + this match { + case (_: ModuleAspect | _: internal.BaseModule.ModuleClone) => desiredName + case _ => Builder.globalNamespace.name(desiredName) + } } catch { case e: NullPointerException => throwException( s"Error: desiredName of ${this.getClass.getName} is null. Did you evaluate 'name' before all values needed by desiredName were available?", e) diff --git a/core/src/main/scala/chisel3/RawModule.scala b/core/src/main/scala/chisel3/RawModule.scala index de93e781..5bcd4dbd 100644 --- a/core/src/main/scala/chisel3/RawModule.scala +++ b/core/src/main/scala/chisel3/RawModule.scala @@ -57,7 +57,7 @@ abstract class RawModule(implicit moduleCompileOptions: CompileOptions) } - private[chisel3] override def generateComponent(): Component = { + private[chisel3] override def generateComponent(): Option[Component] = { require(!_closed, "Can't generate module more than once") _closed = true @@ -130,7 +130,7 @@ abstract class RawModule(implicit moduleCompileOptions: CompileOptions) } val component = DefModule(this, name, firrtlPorts, invalidateCommands ++ getCommands) _component = Some(component) - component + _component } private[chisel3] def initializeInParent(parentCompileOptions: CompileOptions): Unit = { @@ -221,7 +221,7 @@ package object internal { // Allow access to bindings from the compatibility package protected def _compatIoPortBound() = portsContains(_io) - private[chisel3] override def generateComponent(): Component = { + private[chisel3] override def generateComponent(): Option[Component] = { _compatAutoWrapPorts() // pre-IO(...) compatibility hack // Restrict IO to just io, clock, and reset diff --git a/core/src/main/scala/chisel3/internal/Builder.scala b/core/src/main/scala/chisel3/internal/Builder.scala index e1e4d460..35c4bdf9 100644 --- a/core/src/main/scala/chisel3/internal/Builder.scala +++ b/core/src/main/scala/chisel3/internal/Builder.scala @@ -84,7 +84,7 @@ trait InstanceId { private[chisel3] trait HasId extends InstanceId { private[chisel3] def _onModuleClose: Unit = {} - private[chisel3] val _parent: Option[BaseModule] = Builder.currentModule + private[chisel3] var _parent: Option[BaseModule] = Builder.currentModule private[chisel3] val _id: Long = Builder.idGen.next diff --git a/core/src/main/scala/chisel3/internal/firrtl/Converter.scala b/core/src/main/scala/chisel3/internal/firrtl/Converter.scala index 40d3691c..093d4848 100644 --- a/core/src/main/scala/chisel3/internal/firrtl/Converter.scala +++ b/core/src/main/scala/chisel3/internal/firrtl/Converter.scala @@ -24,16 +24,24 @@ private[chisel3] object Converter { case Percent => ("%%", List.empty) } + private def reportInternalError(msg: String): Nothing = { + val link = "https://github.com/chipsalliance/chisel3/issues/new" + val fullMsg = s"Internal Error! $msg This is a bug in Chisel, please file an issue at '$link'" + throwException(fullMsg) + } + def getRef(id: HasId, sourceInfo: SourceInfo): Arg = id.getOptionRef.getOrElse { val module = id._parent.map(m => s" '$id' was defined in module '$m'.").getOrElse("") val loc = sourceInfo.makeMessage(" " + _) - val link = "https://github.com/chipsalliance/chisel3/issues/new" - val msg = s"Internal error! Could not get ref for '$id'$loc!$module " + - s"This is a bug in Chisel, please file an issue at '$link'." - throwException(msg) + reportInternalError(s"Could not get ref for '$id'$loc!$module") } + private def clonedModuleIOError(mod: BaseModule, name: String, sourceInfo: SourceInfo): Nothing = { + val loc = sourceInfo.makeMessage(" " + _) + reportInternalError(s"Trying to convert a cloned IO of $mod inside of $mod itself$loc!") + } + def convert(info: SourceInfo): fir.Info = info match { case _: NoSourceInfo => fir.NoInfo case SourceLine(fn, line, col) => fir.FileInfo(fir.StringLit(s"$fn $line:$col")) @@ -65,6 +73,9 @@ private[chisel3] object Converter { case ModuleIO(mod, name) => if (mod eq ctx.id) fir.Reference(name, fir.UnknownType) else fir.SubField(fir.Reference(getRef(mod, info).name, fir.UnknownType), name, fir.UnknownType) + case ModuleCloneIO(mod, name) => + if (mod eq ctx.id) clonedModuleIOError(mod, name, info) + else fir.Reference(name) case u @ ULit(n, UnknownWidth()) => fir.UIntLiteral(n, fir.IntWidth(u.minWidth)) case ULit(n, w) => diff --git a/core/src/main/scala/chisel3/internal/firrtl/IR.scala b/core/src/main/scala/chisel3/internal/firrtl/IR.scala index 5dc72a43..1d77802b 100644 --- a/core/src/main/scala/chisel3/internal/firrtl/IR.scala +++ b/core/src/main/scala/chisel3/internal/firrtl/IR.scala @@ -165,9 +165,18 @@ case class ModuleIO(mod: BaseModule, name: String) extends Arg { override def fullName(ctx: Component): String = if (mod eq ctx.id) name else s"${mod.getRef.name}.$name" } -case class Slot(imm: Node, name: String) extends Arg { +// For use with CloneModuleAsRecord +// Note that `name` is the name of the module instance whereas in ModuleIO it's the name of the port +// The names of ports inside of a ModuleCloneIO are the names of the Slots +case class ModuleCloneIO(mod: BaseModule, name: String) extends Arg { override def fullName(ctx: Component): String = - if (imm.fullName(ctx).isEmpty) name else s"${imm.fullName(ctx)}.${name}" + if (mod eq ctx.id) "" else name +} +case class Slot(imm: Node, name: String) extends Arg { + override def fullName(ctx: Component): String = { + val immName = imm.fullName(ctx) + if (immName.isEmpty) name else s"$immName.$name" + } } case class Index(imm: Arg, value: Arg) extends Arg { def name: String = s"[$value]" -- cgit v1.2.3 From b87107ad41e948de9da9c349505de414b1a9db7f Mon Sep 17 00:00:00 2001 From: Jack Koenig Date: Mon, 28 Jun 2021 14:07:03 -0700 Subject: Set refs for ModuleClone and ClonePorts in less hacky way --- core/src/main/scala/chisel3/Module.scala | 56 +++++++++++----------- core/src/main/scala/chisel3/RawModule.scala | 2 + .../main/scala/chisel3/internal/firrtl/IR.scala | 12 +++-- 3 files changed, 39 insertions(+), 31 deletions(-) (limited to 'core/src') diff --git a/core/src/main/scala/chisel3/Module.scala b/core/src/main/scala/chisel3/Module.scala index 77735583..8a914fbc 100644 --- a/core/src/main/scala/chisel3/Module.scala +++ b/core/src/main/scala/chisel3/Module.scala @@ -184,48 +184,44 @@ package internal { object BaseModule { // Private internal class to serve as a _parent for Data in cloned ports - private[chisel3] class ModuleClone(proto: BaseModule) extends BaseModule { + private[chisel3] class ModuleClone(_proto: BaseModule) extends BaseModule { + // ClonePorts that hold the bound ports for this module + // Used for setting the refs of both this module and the Record + private[BaseModule] var _portsRecord: Record = _ // Don't generate a component, but point to the one for the cloned Module private[chisel3] def generateComponent(): Option[Component] = { - _component = proto._component + _component = _proto._component None } // This module doesn't acutally exist in the FIRRTL so no initialization to do private[chisel3] def initializeInParent(parentCompileOptions: CompileOptions): Unit = () - override def desiredName: String = proto.name + override def desiredName: String = _proto.name + + private[chisel3] def setRefAndPortsRef(namespace: Namespace): Unit = { + val record = _portsRecord + // Use .forceName to re-use default name resolving behavior + record.forceName(None, default=this.desiredName, namespace) + // Now take the Ref that forceName set and convert it to the correct Arg + val instName = record.getRef match { + case Ref(name) => name + case bad => throwException(s"Internal Error! Cloned-module Record $record has unexpected ref $bad") + } + // Set both the record and the module to have the same instance name + record.setRef(ModuleCloneIO(_proto, instName), force=true) // force because we did .forceName first + this.setRef(Ref(instName)) + } } /** Record type returned by CloneModuleAsRecord * * @note These are not true Data (the Record doesn't correspond to anything in the emitted * FIRRTL yet its elements *do*) so have some very specialized behavior. - * @param proto Optional pointer to the Module we are a clone of. Set for first instance, unset - * for clones */ - private[chisel3] class ClonePorts (proto: Option[BaseModule], elts: Data*)(implicit compileOptions: CompileOptions) extends Record { + private[chisel3] class ClonePorts (elts: Data*)(implicit compileOptions: CompileOptions) extends Record { val elements = ListMap(elts.map(d => d.instanceName -> d.cloneTypeFull): _*) def apply(field: String) = elements(field) - override def cloneType = (new ClonePorts(None, elts: _*)).asInstanceOf[this.type] - - // Because ClonePorts instances are *not* created inside of their parent module, but rather, - // their parent's parent, we have to intercept the standard setRef and replace it with our own - // special Ref type. - // This only applies to ClonePorts created in cloneIORecord, any clones of these Records have - // normal behavior. - // Also, the name of ClonePorts Records needs to be propagated to their parent ModuleClone - // since we have no other way of setting the instance name for those. - private[chisel3] override def setRef(imm: Arg, force: Boolean): Unit = { - val immx = (proto, imm) match { - case (Some(mod), Ref(name)) => - // Our _parent is a ModuleClone that needs its ref to match ours for .toAbsoluteTarget - _parent.foreach(_.setRef(Ref(name), force=true)) - // Return a specialize-ref that will do the right thing - ModuleCloneIO(mod, name) - case _ => imm - } - super.setRef(immx, force) - } + override def cloneType = (new ClonePorts(elts: _*)).asInstanceOf[this.type] } // Recursively set the parent of the start Data and any children (eg. in an Aggregate) @@ -243,12 +239,16 @@ package internal { private[chisel3] def cloneIORecord(proto: BaseModule)(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): ClonePorts = { require(proto.isClosed, "Can't clone a module before module close") + // Fake Module to serve as the _parent of the cloned ports + // We make this before clonePorts because we want it to come up first in naming in + // currentModule + val cloneParent = Module(new ModuleClone(proto)) // We don't create this inside the ModuleClone because we need the ref to be set by the // currentModule (and not clonePorts) - val clonePorts = new ClonePorts(Some(proto), proto.getModulePorts: _*) - val cloneParent = Module(new ModuleClone(proto)) + val clonePorts = new ClonePorts(proto.getModulePorts: _*) clonePorts.bind(PortBinding(cloneParent)) setAllParents(clonePorts, Some(cloneParent)) + cloneParent._portsRecord = clonePorts // Normally handled during Module construction but ClonePorts really lives in its parent's parent if (!compileOptions.explicitInvalidate) { pushCommand(DefInvalid(sourceInfo, clonePorts.ref)) diff --git a/core/src/main/scala/chisel3/RawModule.scala b/core/src/main/scala/chisel3/RawModule.scala index 5bcd4dbd..4a60ca47 100644 --- a/core/src/main/scala/chisel3/RawModule.scala +++ b/core/src/main/scala/chisel3/RawModule.scala @@ -7,6 +7,7 @@ import scala.util.Try import scala.language.experimental.macros import chisel3.experimental.{BaseModule, BaseSim} import chisel3.internal._ +import chisel3.internal.BaseModule.ModuleClone import chisel3.internal.Builder._ import chisel3.internal.firrtl._ import chisel3.internal.sourceinfo.UnlocatableSourceInfo @@ -74,6 +75,7 @@ abstract class RawModule(implicit moduleCompileOptions: CompileOptions) // All suggestions are in, force names to every node. for (id <- getIds) { id match { + case id: ModuleClone => id.setRefAndPortsRef(_namespace) // special handling case id: BaseModule => id.forceName(None, default=id.desiredName, _namespace) case id: MemBase[_] => id.forceName(None, default="MEM", _namespace) case id: BaseSim => id.forceName(None, default="SIM", _namespace) diff --git a/core/src/main/scala/chisel3/internal/firrtl/IR.scala b/core/src/main/scala/chisel3/internal/firrtl/IR.scala index 1d77802b..a4f6d26d 100644 --- a/core/src/main/scala/chisel3/internal/firrtl/IR.scala +++ b/core/src/main/scala/chisel3/internal/firrtl/IR.scala @@ -161,15 +161,21 @@ case class IntervalLit(n: BigInt, w: Width, binaryPoint: BinaryPoint) extends Li } case class Ref(name: String) extends Arg +/** Arg for ports of Modules + * @param mod the module this port belongs to + * @param name the name of the port + */ case class ModuleIO(mod: BaseModule, name: String) extends Arg { override def fullName(ctx: Component): String = if (mod eq ctx.id) name else s"${mod.getRef.name}.$name" } -// For use with CloneModuleAsRecord -// Note that `name` is the name of the module instance whereas in ModuleIO it's the name of the port -// The names of ports inside of a ModuleCloneIO are the names of the Slots +/** Ports of cloned modules (CloneModuleAsRecord) + * @param mod The original module for which these ports are a clone + * @param name the name of the module instance + */ case class ModuleCloneIO(mod: BaseModule, name: String) extends Arg { override def fullName(ctx: Component): String = + // NOTE: mod eq ctx.id only occurs in Target and Named-related APIs if (mod eq ctx.id) "" else name } case class Slot(imm: Node, name: String) extends Arg { -- cgit v1.2.3 From f210909e11f95cbc033898b22d3498ac7a7a87bc Mon Sep 17 00:00:00 2001 From: Jiuyang Liu Date: Tue, 29 Jun 2021 09:47:43 +0800 Subject: deprecate getPorts with modulePorts. (#1945) * deprecate getPorts with modulePorts. * add doc to fullModulePorts and update deprecation notes. Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>--- core/src/main/scala/chisel3/Data.scala | 4 +++- core/src/main/scala/chisel3/RawModule.scala | 1 + 2 files changed, 4 insertions(+), 1 deletion(-) (limited to 'core/src') diff --git a/core/src/main/scala/chisel3/Data.scala b/core/src/main/scala/chisel3/Data.scala index 0832161e..5513035b 100644 --- a/core/src/main/scala/chisel3/Data.scala +++ b/core/src/main/scala/chisel3/Data.scala @@ -156,7 +156,9 @@ package experimental { // with compiled artifacts (vs. elaboration-time reflection)? def modulePorts(target: BaseModule): Seq[(String, Data)] = target.getChiselPorts - // Returns all module ports with underscore-qualified names + /** Returns all module ports with underscore-qualified names + * return includes [[Module.clock]] and [[Module.reset]] + */ def fullModulePorts(target: BaseModule): Seq[(String, Data)] = { def getPortNames(name: String, data: Data): Seq[(String, Data)] = Seq(name -> data) ++ (data match { case _: Element => Seq() diff --git a/core/src/main/scala/chisel3/RawModule.scala b/core/src/main/scala/chisel3/RawModule.scala index 4a60ca47..fadb8dae 100644 --- a/core/src/main/scala/chisel3/RawModule.scala +++ b/core/src/main/scala/chisel3/RawModule.scala @@ -36,6 +36,7 @@ abstract class RawModule(implicit moduleCompileOptions: CompileOptions) // // For debuggers/testers, TODO: refactor out into proper public API private var _firrtlPorts: Option[Seq[firrtl.Port]] = None + @deprecated("Use DataMirror.fullModulePorts instead. this API will be removed in Chisel 3.6", "Chisel 3.5") lazy val getPorts = _firrtlPorts.get val compileOptions = moduleCompileOptions -- cgit v1.2.3 From 0531cb53d3cedaff33c2a280e34418f6af5bc6a1 Mon Sep 17 00:00:00 2001 From: Jack Koenig Date: Tue, 29 Jun 2021 15:34:18 -0700 Subject: Restore aop.Select behavior for CloneModuleAsRecord --- core/src/main/scala/chisel3/Module.scala | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'core/src') diff --git a/core/src/main/scala/chisel3/Module.scala b/core/src/main/scala/chisel3/Module.scala index 8a914fbc..f82b6a7b 100644 --- a/core/src/main/scala/chisel3/Module.scala +++ b/core/src/main/scala/chisel3/Module.scala @@ -184,12 +184,14 @@ package internal { object BaseModule { // Private internal class to serve as a _parent for Data in cloned ports - private[chisel3] class ModuleClone(_proto: BaseModule) extends BaseModule { + private[chisel3] class ModuleClone(private[chisel3] val _proto: BaseModule) extends BaseModule { // ClonePorts that hold the bound ports for this module // Used for setting the refs of both this module and the Record private[BaseModule] var _portsRecord: Record = _ // Don't generate a component, but point to the one for the cloned Module private[chisel3] def generateComponent(): Option[Component] = { + require(!_closed, "Can't generate module more than once") + _closed = true _component = _proto._component None } -- cgit v1.2.3 From 25a84b5667614ea3f437b656f1939caba57e6f66 Mon Sep 17 00:00:00 2001 From: Jack Koenig Date: Tue, 29 Jun 2021 16:39:45 -0700 Subject: Change behavior of aop.Select to not include CloneModuleAsRecord Previously, CloneModuleAsRecord clones would result in the same BaseModule object coming up multiple times when using APIs like .instances, .collectDeep, and .getDeep. This was not the intended behavior and can lead to very subtle bugs. --- core/src/main/scala/chisel3/Module.scala | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'core/src') diff --git a/core/src/main/scala/chisel3/Module.scala b/core/src/main/scala/chisel3/Module.scala index f82b6a7b..41fe4554 100644 --- a/core/src/main/scala/chisel3/Module.scala +++ b/core/src/main/scala/chisel3/Module.scala @@ -184,7 +184,7 @@ package internal { object BaseModule { // Private internal class to serve as a _parent for Data in cloned ports - private[chisel3] class ModuleClone(private[chisel3] val _proto: BaseModule) extends BaseModule { + private[chisel3] class ModuleClone(_proto: BaseModule) extends BaseModule { // ClonePorts that hold the bound ports for this module // Used for setting the refs of both this module and the Record private[BaseModule] var _portsRecord: Record = _ -- cgit v1.2.3 From 04caf395c737450c26f59d373d76b567a2b80f0f Mon Sep 17 00:00:00 2001 From: Jack Koenig Date: Thu, 1 Jul 2021 16:33:38 -0700 Subject: Change Chisel warnings to use logger instead of println It also uses the same logger as the Builder so that if we ever refactor that to be passed as an argument, it will be the same logger for both Builder and warning reporting. --- core/src/main/scala/chisel3/internal/Builder.scala | 2 +- core/src/main/scala/chisel3/internal/Error.scala | 25 +++++++++++----------- 2 files changed, 14 insertions(+), 13 deletions(-) (limited to 'core/src') diff --git a/core/src/main/scala/chisel3/internal/Builder.scala b/core/src/main/scala/chisel3/internal/Builder.scala index 35c4bdf9..fef12093 100644 --- a/core/src/main/scala/chisel3/internal/Builder.scala +++ b/core/src/main/scala/chisel3/internal/Builder.scala @@ -652,7 +652,7 @@ private[chisel3] object Builder extends LazyLogging { logger.warn("Elaborating design...") val mod = f mod.forceName(None, mod.name, globalNamespace) - errors.checkpoint() + errors.checkpoint(logger) logger.warn("Done elaborating.") (Circuit(components.last.name, components.toSeq, annotations.toSeq), mod) diff --git a/core/src/main/scala/chisel3/internal/Error.scala b/core/src/main/scala/chisel3/internal/Error.scala index 454be360..d6e0c0e6 100644 --- a/core/src/main/scala/chisel3/internal/Error.scala +++ b/core/src/main/scala/chisel3/internal/Error.scala @@ -4,6 +4,7 @@ package chisel3.internal import scala.annotation.tailrec import scala.collection.mutable.{ArrayBuffer, LinkedHashMap} +import _root_.logger.Logger object ExceptionHelpers { @@ -184,31 +185,31 @@ private[chisel3] class ErrorLog { } /** Throw an exception if any errors have yet occurred. */ - def checkpoint(): Unit = { + def checkpoint(logger: Logger): Unit = { deprecations.foreach { case ((message, sourceLoc), count) => - println(s"${ErrorLog.depTag} $sourceLoc ($count calls): $message") + logger.warn(s"${ErrorLog.depTag} $sourceLoc ($count calls): $message") } - errors foreach println + errors.foreach(e => logger.error(e.toString)) if (!deprecations.isEmpty) { - println(s"${ErrorLog.warnTag} ${Console.YELLOW}There were ${deprecations.size} deprecated function(s) used." + + logger.warn(s"${ErrorLog.warnTag} ${Console.YELLOW}There were ${deprecations.size} deprecated function(s) used." + s" These may stop compiling in a future release - you are encouraged to fix these issues.${Console.RESET}") - println(s"${ErrorLog.warnTag} Line numbers for deprecations reported by Chisel may be inaccurate; enable scalac compiler deprecation warnings via either of the following methods:") - println(s"${ErrorLog.warnTag} In the sbt interactive console, enter:") - println(s"""${ErrorLog.warnTag} set scalacOptions in ThisBuild ++= Seq("-unchecked", "-deprecation")""") - println(s"${ErrorLog.warnTag} or, in your build.sbt, add the line:") - println(s"""${ErrorLog.warnTag} scalacOptions := Seq("-unchecked", "-deprecation")""") + logger.warn(s"${ErrorLog.warnTag} Line numbers for deprecations reported by Chisel may be inaccurate; enable scalac compiler deprecation warnings via either of the following methods:") + logger.warn(s"${ErrorLog.warnTag} In the sbt interactive console, enter:") + logger.warn(s"""${ErrorLog.warnTag} set scalacOptions in ThisBuild ++= Seq("-unchecked", "-deprecation")""") + logger.warn(s"${ErrorLog.warnTag} or, in your build.sbt, add the line:") + logger.warn(s"""${ErrorLog.warnTag} scalacOptions := Seq("-unchecked", "-deprecation")""") } val allErrors = errors.filter(_.isFatal) val allWarnings = errors.filter(!_.isFatal) if (!allWarnings.isEmpty && !allErrors.isEmpty) { - println(s"${ErrorLog.errTag} There were ${Console.RED}${allErrors.size} error(s)${Console.RESET} and ${Console.YELLOW}${allWarnings.size} warning(s)${Console.RESET} during hardware elaboration.") + logger.warn(s"${ErrorLog.errTag} There were ${Console.RED}${allErrors.size} error(s)${Console.RESET} and ${Console.YELLOW}${allWarnings.size} warning(s)${Console.RESET} during hardware elaboration.") } else if (!allWarnings.isEmpty) { - println(s"${ErrorLog.warnTag} There were ${Console.YELLOW}${allWarnings.size} warning(s)${Console.RESET} during hardware elaboration.") + logger.warn(s"${ErrorLog.warnTag} There were ${Console.YELLOW}${allWarnings.size} warning(s)${Console.RESET} during hardware elaboration.") } else if (!allErrors.isEmpty) { - println(s"${ErrorLog.errTag} There were ${Console.RED}${allErrors.size} error(s)${Console.RESET} during hardware elaboration.") + logger.warn(s"${ErrorLog.errTag} There were ${Console.RED}${allErrors.size} error(s)${Console.RESET} during hardware elaboration.") } if (!allErrors.isEmpty) { -- cgit v1.2.3 From 5fe539c707c88eedbb112f5c6bcea1dfe1d52169 Mon Sep 17 00:00:00 2001 From: Jack Koenig Date: Thu, 1 Jul 2021 16:34:48 -0700 Subject: Add ChiselEnum.safe factory method and avoid warning Previously, ChiselEnum would warn any time a UInt is converted to an Enum. There was no way to suppress this warning. Now there is a factory method (`.safe`) that does not warn and returns (Enum, Bool) where the Bool is the result of calling .isValid on an Enum object. The regular UInt cast is also now smarter and will not warn if all bitvectors of the width of the Enum are legal states. --- core/src/main/scala/chisel3/StrongEnum.scala | 34 ++++++++++++++++++++++++---- 1 file changed, 30 insertions(+), 4 deletions(-) (limited to 'core/src') diff --git a/core/src/main/scala/chisel3/StrongEnum.scala b/core/src/main/scala/chisel3/StrongEnum.scala index 7d328eb7..1d0e04d3 100644 --- a/core/src/main/scala/chisel3/StrongEnum.scala +++ b/core/src/main/scala/chisel3/StrongEnum.scala @@ -131,7 +131,7 @@ abstract class EnumType(private val factory: EnumFactory, selfAnnotating: Boolea if (litOption.isDefined) { true.B } else { - factory.all.map(this === _).reduce(_ || _) + if (factory.isTotal) true.B else factory.all.map(this === _).reduce(_ || _) } } @@ -233,6 +233,12 @@ abstract class EnumFactory { private[chisel3] val enumTypeName = getClass.getName.init + // Do all bitvectors of this Enum's width represent legal states? + private[chisel3] def isTotal: Boolean = { + (this.getWidth < 31) && // guard against Integer overflow + (enumRecords.size == (1 << this.getWidth)) + } + private[chisel3] def globalAnnotation: EnumDefChiselAnnotation = EnumDefChiselAnnotation(enumTypeName, (enumNames, enumValues).zipped.toMap) @@ -277,7 +283,7 @@ abstract class EnumFactory { def apply(): Type = new Type - def apply(n: UInt)(implicit sourceInfo: SourceInfo, connectionCompileOptions: CompileOptions): Type = { + private def castImpl(n: UInt, warn: Boolean)(implicit sourceInfo: SourceInfo, connectionCompileOptions: CompileOptions): Type = { if (n.litOption.isDefined) { enumInstances.find(_.litValue == n.litValue) match { case Some(result) => result @@ -288,8 +294,9 @@ abstract class EnumFactory { } else if (n.getWidth > this.getWidth) { throwException(s"The UInt being cast to $enumTypeName is wider than $enumTypeName's width ($getWidth)") } else { - Builder.warning(s"Casting non-literal UInt to $enumTypeName. You can check that its value is legal by calling isValid") - + if (warn && !this.isTotal) { + Builder.warning(s"Casting non-literal UInt to $enumTypeName. You can use $enumTypeName.safe to cast without this warning.") + } val glue = Wire(new UnsafeEnum(width)) glue := n val result = Wire(new Type) @@ -297,6 +304,25 @@ abstract class EnumFactory { result } } + + /** Cast an [[UInt]] to the type of this Enum + * + * @note will give a Chisel elaboration time warning if the argument could hit invalid states + * @param n the UInt to cast + * @return the equivalent Enum to the value of the cast UInt + */ + def apply(n: UInt)(implicit sourceInfo: SourceInfo, connectionCompileOptions: CompileOptions): Type = castImpl(n, warn = true) + + /** Safely cast an [[UInt]] to the type of this Enum + * + * @param n the UInt to cast + * @return the equivalent Enum to the value of the cast UInt and a Bool indicating if the + * Enum is valid + */ + def safe(n: UInt)(implicit sourceInfo: SourceInfo, connectionCompileOptions: CompileOptions): (Type, Bool) = { + val t = castImpl(n, warn = false) + (t, t.isValid) + } } -- cgit v1.2.3 From 503ae520e7f997bcbc639b79869c9a4214d402ed Mon Sep 17 00:00:00 2001 From: Deborah Soung Date: Tue, 6 Jul 2021 14:40:59 -0700 Subject: Make printf return BaseSim subclass so it can be named/annotated (#1992) --- core/src/main/scala/chisel3/Printf.scala | 22 ++++++++++++++-------- .../experimental/verification/package.scala | 17 +++++++++-------- .../scala/chisel3/internal/firrtl/Converter.scala | 4 ++-- .../main/scala/chisel3/internal/firrtl/IR.scala | 2 +- 4 files changed, 26 insertions(+), 19 deletions(-) (limited to 'core/src') diff --git a/core/src/main/scala/chisel3/Printf.scala b/core/src/main/scala/chisel3/Printf.scala index 7cbd1918..cf7821b8 100644 --- a/core/src/main/scala/chisel3/Printf.scala +++ b/core/src/main/scala/chisel3/Printf.scala @@ -3,11 +3,10 @@ package chisel3 import scala.language.experimental.macros - import chisel3.internal._ import chisel3.internal.Builder.pushCommand -import chisel3.internal.firrtl._ import chisel3.internal.sourceinfo.SourceInfo +import chisel3.experimental.BaseSim /** Prints a message in simulation * @@ -34,6 +33,9 @@ object printf { formatIn map escaped mkString "" } + /** Named class for [[printf]]s. */ + final class Printf(val pable: Printable) extends BaseSim + /** Prints a message in simulation * * Prints a message every cycle. If defined within the scope of a [[when]] block, the message @@ -71,7 +73,7 @@ object printf { * @param fmt printf format string * @param data format string varargs containing data to print */ - def apply(fmt: String, data: Bits*)(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Unit = + def apply(fmt: String, data: Bits*)(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Printf = apply(Printable.pack(fmt, data:_*)) /** Prints a message in simulation * @@ -87,16 +89,20 @@ object printf { * @see [[Printable]] documentation * @param pable [[Printable]] to print */ - def apply(pable: Printable)(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Unit = { + def apply(pable: Printable)(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Printf = { + var printfId: Printf = null when (!Module.reset.asBool) { - printfWithoutReset(pable) + printfId = printfWithoutReset(pable) } + printfId } - private[chisel3] def printfWithoutReset(pable: Printable)(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Unit = { + private[chisel3] def printfWithoutReset(pable: Printable)(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Printf = { val clock = Builder.forcedClock - pushCommand(Printf(sourceInfo, clock.ref, pable)) + val printfId = new Printf(pable) + pushCommand(chisel3.internal.firrtl.Printf(printfId, sourceInfo, clock.ref, pable)) + printfId } - private[chisel3] def printfWithoutReset(fmt: String, data: Bits*)(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Unit = + private[chisel3] def printfWithoutReset(fmt: String, data: Bits*)(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Printf = printfWithoutReset(Printable.pack(fmt, data:_*)) } diff --git a/core/src/main/scala/chisel3/experimental/verification/package.scala b/core/src/main/scala/chisel3/experimental/verification/package.scala index ca15a5c4..190083fd 100644 --- a/core/src/main/scala/chisel3/experimental/verification/package.scala +++ b/core/src/main/scala/chisel3/experimental/verification/package.scala @@ -9,16 +9,11 @@ import chisel3.internal.sourceinfo.SourceInfo package object verification { - /** Named class for assertions. */ - final class Assert(val predicate: Bool) extends BaseSim - - /** Named class for assumes. */ - final class Assume(val predicate: Bool) extends BaseSim + object assert { + /** Named class for assertions. */ + final class Assert(private[chisel3] val predicate: Bool) extends BaseSim - /** Named class for covers. */ - final class Cover(val predicate: Bool) extends BaseSim - object assert { def apply(predicate: Bool, msg: String = "")( implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Assert = { @@ -32,6 +27,9 @@ package object verification { } object assume { + /** Named class for assumes. */ + final class Assume(private[chisel3] val predicate: Bool) extends BaseSim + def apply(predicate: Bool, msg: String = "")( implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Assume = { @@ -45,6 +43,9 @@ package object verification { } object cover { + /** Named class for covers. */ + final class Cover(private[chisel3] val predicate: Bool) extends BaseSim + def apply(predicate: Bool, msg: String = "")( implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Cover = { diff --git a/core/src/main/scala/chisel3/internal/firrtl/Converter.scala b/core/src/main/scala/chisel3/internal/firrtl/Converter.scala index 093d4848..8efb2abc 100644 --- a/core/src/main/scala/chisel3/internal/firrtl/Converter.scala +++ b/core/src/main/scala/chisel3/internal/firrtl/Converter.scala @@ -143,10 +143,10 @@ private[chisel3] object Converter { Some(fir.DefInstance(convert(info), e.name, id.name)) case Stop(info, clock, ret) => Some(fir.Stop(convert(info), ret, convert(clock, ctx, info), firrtl.Utils.one)) - case Printf(info, clock, pable) => + case e @ Printf(_, info, clock, pable) => val (fmt, args) = unpack(pable, ctx) Some(fir.Print(convert(info), fir.StringLit(fmt), - args.map(a => convert(a, ctx, info)), convert(clock, ctx, info), firrtl.Utils.one)) + args.map(a => convert(a, ctx, info)), convert(clock, ctx, info), firrtl.Utils.one, e.name)) case e @ Verification(_, op, info, clk, pred, msg) => val firOp = op match { case Formal.Assert => fir.Formal.Assert diff --git a/core/src/main/scala/chisel3/internal/firrtl/IR.scala b/core/src/main/scala/chisel3/internal/firrtl/IR.scala index a4f6d26d..5796522c 100644 --- a/core/src/main/scala/chisel3/internal/firrtl/IR.scala +++ b/core/src/main/scala/chisel3/internal/firrtl/IR.scala @@ -773,7 +773,7 @@ case class Attach(sourceInfo: SourceInfo, locs: Seq[Node]) extends Command case class ConnectInit(sourceInfo: SourceInfo, loc: Node, exp: Arg) extends Command case class Stop(sourceInfo: SourceInfo, clock: Arg, ret: Int) extends Command case class Port(id: Data, dir: SpecifiedDirection) -case class Printf(sourceInfo: SourceInfo, clock: Arg, pable: Printable) extends Command +case class Printf(id: printf.Printf, sourceInfo: SourceInfo, clock: Arg, pable: Printable) extends Definition object Formal extends Enumeration { val Assert = Value("assert") val Assume = Value("assume") -- cgit v1.2.3 From f1e37900170124254f3cf4599a45e7a485c17a91 Mon Sep 17 00:00:00 2001 From: Schuyler Eldridge Date: Wed, 7 Jul 2021 21:05:33 -0400 Subject: Update docs on dontTouch as optimization barrier (#2015) Change the Scaladoc for the dontTouch utility. Indicate that this is an _optimization barrier_ and not just a guarantee that the signal won't be removed. The optimization barrier interpretation is the current implementation in the Scala FIRRTL Compiler. Signed-off-by: Schuyler Eldridge Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>--- core/src/main/scala/chisel3/dontTouch.scala | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'core/src') diff --git a/core/src/main/scala/chisel3/dontTouch.scala b/core/src/main/scala/chisel3/dontTouch.scala index 0487a567..e679f1a4 100644 --- a/core/src/main/scala/chisel3/dontTouch.scala +++ b/core/src/main/scala/chisel3/dontTouch.scala @@ -5,7 +5,8 @@ package chisel3 import chisel3.experimental.{ChiselAnnotation, annotate, requireIsHardware} import firrtl.transforms.DontTouchAnnotation -/** Marks that a signal should not be removed by Chisel and Firrtl optimization passes +/** Marks that a signal is an optimization barrier to Chisel and the FIRRTL compiler. This has the effect of + * guaranteeing that a signal will not be removed. * * @example {{{ * class MyModule extends Module { @@ -21,9 +22,11 @@ import firrtl.transforms.DontTouchAnnotation * @note Calling this on [[Data]] creates an annotation that Chisel emits to a separate annotations * file. This file must be passed to FIRRTL independently of the `.fir` file. The execute methods * in [[chisel3.Driver]] will pass the annotations to FIRRTL automatically. + * @note Because this is an optimization barrier, constants will not be propagated through a signal marked as + * dontTouch. */ object dontTouch { - /** Marks a signal to be preserved in Chisel and Firrtl + /** Mark a signal as an optimization barrier to Chisel and FIRRTL. * * @note Requires the argument to be bound to hardware * @param data The signal to be marked -- cgit v1.2.3 From bb520b8573328fda5f7b3c3892e6995fbe1b4239 Mon Sep 17 00:00:00 2001 From: Verneri Hirvonen Date: Thu, 8 Jul 2021 18:59:12 +0300 Subject: Add `isOneOf` method to `ChiselEnum` (#1966) * Add @ekiwi's code as a starting point * Add test for ChiselEnum isOneOf method * Make isOneOfTester naming consistent with other testers * Add scaladoc comments for isOneOf * Add isOneOf tests that use the method that takes variable number of args * Add guide level documentation example for isOneOf--- core/src/main/scala/chisel3/StrongEnum.scala | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) (limited to 'core/src') diff --git a/core/src/main/scala/chisel3/StrongEnum.scala b/core/src/main/scala/chisel3/StrongEnum.scala index 1d0e04d3..b3d7cf7d 100644 --- a/core/src/main/scala/chisel3/StrongEnum.scala +++ b/core/src/main/scala/chisel3/StrongEnum.scala @@ -135,6 +135,24 @@ abstract class EnumType(private val factory: EnumFactory, selfAnnotating: Boolea } } + /** Test if this enumeration is equal to any of the values in a given sequence + * + * @param s a [[scala.collection.Seq$ Seq]] of enumeration values to look for + * @return a hardware [[Bool]] that indicates if this value matches any of the given values + */ + final def isOneOf(s: Seq[EnumType])(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Bool = { + VecInit(s.map(this === _)).asUInt().orR() + } + + /** Test if this enumeration is equal to any of the values given as arguments + * + * @param u1 the first value to look for + * @param u2 zero or more additional values to look for + * @return a hardware [[Bool]] that indicates if this value matches any of the given values + */ + final def isOneOf(u1: EnumType, u2: EnumType*)(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Bool + = isOneOf(u1 +: u2.toSeq) + def next(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): this.type = { if (litOption.isDefined) { val index = factory.all.indexOf(this) -- cgit v1.2.3 From 16c0b53e04f3a78ddaaa382936cd660523a57199 Mon Sep 17 00:00:00 2001 From: Jack Koenig Date: Thu, 8 Jul 2021 15:30:28 -0700 Subject: Fix chisel3 <> for Bundles that contain compatibility Bundles (#2023) BiConnect in chisel3 delegates to FIRRTL <- semantics whenever it hits a Bundle defined in `import Chisel._`. Because chisel3 <> is commutative it needs to be mindful of flippedness when emitting a FIRRTL <- (which is *not* commutative).--- .../main/scala/chisel3/internal/BiConnect.scala | 25 +++++++++++++++------- 1 file changed, 17 insertions(+), 8 deletions(-) (limited to 'core/src') diff --git a/core/src/main/scala/chisel3/internal/BiConnect.scala b/core/src/main/scala/chisel3/internal/BiConnect.scala index 1ee149ee..fcea4fe2 100644 --- a/core/src/main/scala/chisel3/internal/BiConnect.scala +++ b/core/src/main/scala/chisel3/internal/BiConnect.scala @@ -113,14 +113,23 @@ private[chisel3] object BiConnect { } } } - // Handle Records defined in Chisel._ code (change to NotStrict) - case (left_r: Record, right_r: Record) => (left_r.compileOptions, right_r.compileOptions) match { - case (ExplicitCompileOptions.NotStrict, _) => - left_r.bulkConnect(right_r)(sourceInfo, ExplicitCompileOptions.NotStrict) - case (_, ExplicitCompileOptions.NotStrict) => - left_r.bulkConnect(right_r)(sourceInfo, ExplicitCompileOptions.NotStrict) - case _ => recordConnect(sourceInfo, connectCompileOptions, left_r, right_r, context_mod) - } + // Handle Records defined in Chisel._ code by emitting a FIRRTL partial connect + case pair @ (left_r: Record, right_r: Record) => + val notStrict = + Seq(left_r.compileOptions, right_r.compileOptions).contains(ExplicitCompileOptions.NotStrict) + if (notStrict) { + // chisel3 <> is commutative but FIRRTL <- is not + val flipped = { + // Everything is flipped when it's the port of a child + val childPort = left_r._parent.get != context_mod + val isFlipped = left_r.direction == ActualDirection.Bidirectional(ActualDirection.Flipped) + isFlipped ^ childPort + } + val (newLeft, newRight) = if (flipped) pair.swap else pair + newLeft.bulkConnect(newRight)(sourceInfo, ExplicitCompileOptions.NotStrict) + } else { + recordConnect(sourceInfo, connectCompileOptions, left_r, right_r, context_mod) + } // Handle Records connected to DontCare (change to NotStrict) case (left_r: Record, DontCare) => -- cgit v1.2.3 From 4b7b771eeced366345779a75987ce552558a1c7e Mon Sep 17 00:00:00 2001 From: Jack Koenig Date: Thu, 8 Jul 2021 17:07:24 -0700 Subject: Make it legal for concrete resets to drive abstract reset (#2018) This has been legal in FIRRTL since v1.2.3 (when reset inference started using a unification-style algorithm) but was never exposed in the Chisel API. Also delete the overridden connects in AsyncReset and ResetType which just duplicate logic from MonoConnect.--- core/src/main/scala/chisel3/Bits.scala | 10 ---------- core/src/main/scala/chisel3/internal/MonoConnect.scala | 2 ++ 2 files changed, 2 insertions(+), 10 deletions(-) (limited to 'core/src') diff --git a/core/src/main/scala/chisel3/Bits.scala b/core/src/main/scala/chisel3/Bits.scala index aa5b1abb..670f6e7a 100644 --- a/core/src/main/scala/chisel3/Bits.scala +++ b/core/src/main/scala/chisel3/Bits.scala @@ -961,11 +961,6 @@ final class ResetType(private[chisel3] val width: Width = Width(1)) extends Elem private[chisel3] def typeEquivalent(that: Data): Boolean = this.getClass == that.getClass - override def connect(that: Data)(implicit sourceInfo: SourceInfo, connectCompileOptions: CompileOptions): Unit = that match { - case _: Reset | DontCare => super.connect(that)(sourceInfo, connectCompileOptions) - case _ => super.badConnect(that)(sourceInfo) - } - override def litOption = None /** Not really supported */ @@ -1008,11 +1003,6 @@ sealed class AsyncReset(private[chisel3] val width: Width = Width(1)) extends El private[chisel3] def typeEquivalent(that: Data): Boolean = this.getClass == that.getClass - override def connect(that: Data)(implicit sourceInfo: SourceInfo, connectCompileOptions: CompileOptions): Unit = that match { - case _: AsyncReset | DontCare => super.connect(that)(sourceInfo, connectCompileOptions) - case _ => super.badConnect(that)(sourceInfo) - } - override def litOption = None /** Not really supported */ diff --git a/core/src/main/scala/chisel3/internal/MonoConnect.scala b/core/src/main/scala/chisel3/internal/MonoConnect.scala index 2155894a..b979ebae 100644 --- a/core/src/main/scala/chisel3/internal/MonoConnect.scala +++ b/core/src/main/scala/chisel3/internal/MonoConnect.scala @@ -103,6 +103,8 @@ private[chisel3] object MonoConnect { elemConnect(sourceInfo, connectCompileOptions, sink_e, source_e, context_mod) case (sink_e: ResetType, source_e: Reset) => elemConnect(sourceInfo, connectCompileOptions, sink_e, source_e, context_mod) + case (sink_e: Reset, source_e: ResetType) => + elemConnect(sourceInfo, connectCompileOptions, sink_e, source_e, context_mod) case (sink_e: EnumType, source_e: UnsafeEnum) => elemConnect(sourceInfo, connectCompileOptions, sink_e, source_e, context_mod) case (sink_e: EnumType, source_e: EnumType) if sink_e.typeEquivalent(source_e) => -- cgit v1.2.3 From 5183ef888274c1d9cc2e22aef95c0e90d86e5122 Mon Sep 17 00:00:00 2001 From: Jack Koenig Date: Fri, 9 Jul 2021 14:29:45 -0700 Subject: Fix chisel3 <> for Bundles that contain compatibility Bundles (Take 2) (#2031) PR #2023 fixed a composition issue for chisel3 biconnects delegating to FIRRTL partial connect when compatibility mode Bundles are elements of chisel3 Bundles. It missed an important case though that caused previously working code to break. The bug is fixed by doing the automatic flipping for compatibility mode Bundles that have "Input" as a direction in addition to those that are "Flipped".--- core/src/main/scala/chisel3/internal/BiConnect.scala | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'core/src') diff --git a/core/src/main/scala/chisel3/internal/BiConnect.scala b/core/src/main/scala/chisel3/internal/BiConnect.scala index fcea4fe2..aa7d7ac3 100644 --- a/core/src/main/scala/chisel3/internal/BiConnect.scala +++ b/core/src/main/scala/chisel3/internal/BiConnect.scala @@ -120,9 +120,10 @@ private[chisel3] object BiConnect { if (notStrict) { // chisel3 <> is commutative but FIRRTL <- is not val flipped = { + import ActualDirection._ // Everything is flipped when it's the port of a child val childPort = left_r._parent.get != context_mod - val isFlipped = left_r.direction == ActualDirection.Bidirectional(ActualDirection.Flipped) + val isFlipped = Seq(Bidirectional(Flipped), Input).contains(left_r.direction) isFlipped ^ childPort } val (newLeft, newRight) = if (flipped) pair.swap else pair -- cgit v1.2.3 From e6c902eaf6f63413ff8f3b12ad8993cf34447413 Mon Sep 17 00:00:00 2001 From: Leway Colin Date: Thu, 15 Jul 2021 07:22:20 +0800 Subject: Fix Cat rename signal (#2011) Co-authored-by: Jack Koenig --- core/src/main/scala/chisel3/SeqUtils.scala | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'core/src') diff --git a/core/src/main/scala/chisel3/SeqUtils.scala b/core/src/main/scala/chisel3/SeqUtils.scala index f6642bcb..da6fc802 100644 --- a/core/src/main/scala/chisel3/SeqUtils.scala +++ b/core/src/main/scala/chisel3/SeqUtils.scala @@ -7,7 +7,7 @@ import chisel3.internal.{prefix, throwException} import scala.language.experimental.macros import chisel3.internal.sourceinfo._ - +import chisel3.internal.plugin.autoNameRecursively private[chisel3] object SeqUtils { /** Concatenates the data elements of the input sequence, in sequence order, together. @@ -26,12 +26,12 @@ private[chisel3] object SeqUtils { } else if (in.tail.isEmpty) { in.head.asUInt } else { - val lo = prefix("lo") { + val lo = autoNameRecursively("lo")(prefix("lo") { asUInt(in.slice(0, in.length/2)) - }.autoSeed("lo") - val hi = prefix("hi") { + }) + val hi = autoNameRecursively("hi")(prefix("hi") { asUInt(in.slice(in.length/2, in.length)) - }.autoSeed("hi") + }) hi ## lo } } -- cgit v1.2.3 From 0666933b3e902192ef57723a92b57d41d50b3f8e Mon Sep 17 00:00:00 2001 From: Jared Barocsi Date: Wed, 28 Jul 2021 14:53:04 -0700 Subject: Bundles can no longer be instantiated with bound hardware (#2046) Co-authored-by: Jack Koenig --- core/src/main/scala/chisel3/Aggregate.scala | 2 ++ 1 file changed, 2 insertions(+) (limited to 'core/src') diff --git a/core/src/main/scala/chisel3/Aggregate.scala b/core/src/main/scala/chisel3/Aggregate.scala index 0031e53b..45ecec36 100644 --- a/core/src/main/scala/chisel3/Aggregate.scala +++ b/core/src/main/scala/chisel3/Aggregate.scala @@ -963,6 +963,8 @@ abstract class Bundle(implicit compileOptions: CompileOptions) extends Record { for (m <- getPublicFields(classOf[Bundle])) { getBundleField(m) match { case Some(d: Data) => + requireIsChiselType(d) + if (nameMap contains m.getName) { require(nameMap(m.getName) eq d) } else { -- cgit v1.2.3 From 5a9b6487fbc5ccf0243f9755ee3cd88ec6036e2c Mon Sep 17 00:00:00 2001 From: anniej-sifive Date: Wed, 4 Aug 2021 12:11:58 -0700 Subject: Added VecInit factory methods (fill,iterate) (#2059) Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>--- core/src/main/scala/chisel3/Aggregate.scala | 30 ++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) (limited to 'core/src') diff --git a/core/src/main/scala/chisel3/Aggregate.scala b/core/src/main/scala/chisel3/Aggregate.scala index 45ecec36..3a766628 100644 --- a/core/src/main/scala/chisel3/Aggregate.scala +++ b/core/src/main/scala/chisel3/Aggregate.scala @@ -590,6 +590,33 @@ object VecInit extends SourceInfoDoc { /** @group SourceInfoTransformMacro */ def do_tabulate[T <: Data](n: Int)(gen: (Int) => T)(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Vec[T] = apply((0 until n).map(i => gen(i))) + + /** Creates a new [[Vec]] of length `n` composed of the result of the given + * function applied to an element of data type T. + * + * @param n number of elements in the vector + * @param gen function that takes in an element T and returns an output + * element of the same type + */ + def fill[T <: Data](n: Int)(gen: => T): Vec[T] = macro VecTransform.fill + + /** @group SourceInfoTransformMacro */ + def do_fill[T <: Data](n: Int)(gen: => T)(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Vec[T] = + apply(Seq.fill(n)(gen)) + + /** Creates a new [[Vec]] of length `n` composed of the result of the given + * function applied to an element of data type T. + * + * @param start First element in the Vec + * @param len Lenth of elements in the Vec + * @param f Function that applies the element T from previous index and returns the output + * element to the next index + */ + def iterate[T <: Data](start: T, len: Int)(f: (T) => T): Vec[T] = macro VecTransform.iterate + + /** @group SourceInfoTransformMacro */ + def do_iterate[T <: Data](start: T, len: Int)(f: (T) => T)(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Vec[T] = + apply(Seq.iterate(start, len)(f)) } /** A trait for [[Vec]]s containing common hardware generators for collection @@ -964,7 +991,7 @@ abstract class Bundle(implicit compileOptions: CompileOptions) extends Record { getBundleField(m) match { case Some(d: Data) => requireIsChiselType(d) - + if (nameMap contains m.getName) { require(nameMap(m.getName) eq d) } else { @@ -1268,3 +1295,4 @@ abstract class Bundle(implicit compileOptions: CompileOptions) extends Record { */ override def toPrintable: Printable = toPrintableHelper(elements.toList.reverse) } + -- cgit v1.2.3 From 1ceb974c55c6785c21ab3934fa750ade0702e276 Mon Sep 17 00:00:00 2001 From: Jack Koenig Date: Thu, 12 Aug 2021 17:04:11 -0700 Subject: Add DataView (#1955) DataView is a mechanism for "viewing" Scala objects as a subtype of `Data`. Often, this is useful for viewing one subtype of `Data`, as another. One can think about a DataView as a cross between a customizable cast and an untagged union. A DataView has a Target type `T`, and a View type `V`. DataView requires that an implementation of `DataProduct` is available for Target types. DataProduct is a type class that provides a way to iterate on `Data` children of objects of implementing types. If a DataView is provided for a type T to a type V, then the function .viewAs[V] (of type T => V) is available. The object (of type T) returned by .viewAs is called a "View" and can be used as both an rvalue and an lvalue. Unlike when using an .asTypeOf cast, connecting to a "View" will connect to the associated field or fields of the underlying Target. DataView also enables .viewAsSupertype which is available for viewing Bundles as a parent Bundle type. It is similar to .viewAs but requires a prototype object of the Target type which will be cloned in order to create the returned View. .viewAsSupertype maps between the corresponding fields of the parent and child Bundle types.--- .../scala/collection/immutable/package.scala | 3 + core/src/main/scala/chisel3/Aggregate.scala | 42 +--- core/src/main/scala/chisel3/Data.scala | 83 ++++++- core/src/main/scala/chisel3/Element.scala | 4 + core/src/main/scala/chisel3/Module.scala | 42 ++-- core/src/main/scala/chisel3/ModuleAspect.scala | 4 +- core/src/main/scala/chisel3/RawModule.scala | 31 +++ .../experimental/dataview/DataProduct.scala | 72 ++++++ .../chisel3/experimental/dataview/DataView.scala | 154 +++++++++++++ .../chisel3/experimental/dataview/package.scala | 251 +++++++++++++++++++++ .../main/scala/chisel3/internal/BiConnect.scala | 6 +- core/src/main/scala/chisel3/internal/Binding.scala | 9 + core/src/main/scala/chisel3/internal/Builder.scala | 66 +++++- .../main/scala/chisel3/internal/MonoConnect.scala | 6 +- .../main/scala/chisel3/internal/firrtl/IR.scala | 7 +- 15 files changed, 708 insertions(+), 72 deletions(-) create mode 100644 core/src/main/scala/chisel3/experimental/dataview/DataProduct.scala create mode 100644 core/src/main/scala/chisel3/experimental/dataview/DataView.scala create mode 100644 core/src/main/scala/chisel3/experimental/dataview/package.scala (limited to 'core/src') diff --git a/core/src/main/scala-2.12/scala/collection/immutable/package.scala b/core/src/main/scala-2.12/scala/collection/immutable/package.scala index 7ae87d9b..c06935d0 100644 --- a/core/src/main/scala-2.12/scala/collection/immutable/package.scala +++ b/core/src/main/scala-2.12/scala/collection/immutable/package.scala @@ -10,4 +10,7 @@ package object immutable { val VectorMap = ListMap type VectorMap[K, +V] = ListMap[K, V] + + val LazyList = Stream + type LazyList[+A] = Stream[A] } diff --git a/core/src/main/scala/chisel3/Aggregate.scala b/core/src/main/scala/chisel3/Aggregate.scala index 3a766628..58bc5ccb 100644 --- a/core/src/main/scala/chisel3/Aggregate.scala +++ b/core/src/main/scala/chisel3/Aggregate.scala @@ -3,6 +3,7 @@ package chisel3 import chisel3.experimental.VecLiterals.AddVecLiteralConstructor +import chisel3.experimental.dataview.{InvalidViewException, isView} import scala.collection.immutable.{SeqMap, VectorMap} import scala.collection.mutable.{HashSet, LinkedHashMap} @@ -88,44 +89,6 @@ sealed abstract class Aggregate extends Data { } } - // Returns pairs of all fields, element-level and containers, in a Record and their path names - private[chisel3] def getRecursiveFields(data: Data, path: String): Seq[(Data, String)] = data match { - case data: Record => - data.elements.map { case (fieldName, fieldData) => - getRecursiveFields(fieldData, s"$path.$fieldName") - }.fold(Seq(data -> path)) { - _ ++ _ - } - case data: Vec[_] => - data.getElements.zipWithIndex.map { case (fieldData, fieldIndex) => - getRecursiveFields(fieldData, path = s"$path($fieldIndex)") - }.fold(Seq(data -> path)) { - _ ++ _ - } - case data => Seq(data -> path) // we don't support or recurse into other Aggregate types here - } - - - // Returns pairs of corresponding fields between two Records of the same type - private[chisel3] def getMatchedFields(x: Data, y: Data): Seq[(Data, Data)] = (x, y) match { - case (x: Element, y: Element) => - require(x typeEquivalent y) - Seq(x -> y) - case (x: Record, y: Record) => - (x.elements zip y.elements).map { case ((xName, xElt), (yName, yElt)) => - require(xName == yName) // assume fields returned in same, deterministic order - getMatchedFields(xElt, yElt) - }.fold(Seq(x -> y)) { - _ ++ _ - } - case (x: Vec[_], y: Vec[_]) => - (x.getElements zip y.getElements).map { case (xElt, yElt) => - getMatchedFields(xElt, yElt) - }.fold(Seq(x -> y)) { - _ ++ _ - } - } - override def do_asUInt(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): UInt = { SeqUtils.do_asUInt(flatten.map(_.asUInt())) } @@ -297,6 +260,9 @@ sealed class Vec[T <: Data] private[chisel3] (gen: => T, val length: Int) def do_apply(p: UInt)(implicit compileOptions: CompileOptions): T = { requireIsHardware(this, "vec") requireIsHardware(p, "vec index") + if (isView(this)) { + throw InvalidViewException("Dynamic indexing of Views is not yet supported") + } val port = gen // Reconstruct the resolvedDirection (in Aggregate.bind), since it's not stored. diff --git a/core/src/main/scala/chisel3/Data.scala b/core/src/main/scala/chisel3/Data.scala index 5513035b..32d83008 100644 --- a/core/src/main/scala/chisel3/Data.scala +++ b/core/src/main/scala/chisel3/Data.scala @@ -2,13 +2,16 @@ package chisel3 +import chisel3.experimental.dataview.reify + import scala.language.experimental.macros -import chisel3.experimental.{Analog, DataMirror, FixedPoint, Interval} +import chisel3.experimental.{Analog, BaseModule, DataMirror, FixedPoint, Interval} import chisel3.internal.Builder.pushCommand import chisel3.internal._ import chisel3.internal.firrtl._ import chisel3.internal.sourceinfo.{DeprecatedSourceInfo, SourceInfo, SourceInfoTransform, UnlocatableSourceInfo} +import scala.collection.immutable.LazyList // Needed for 2.12 alias import scala.util.Try /** User-specified directions. @@ -236,6 +239,62 @@ private[chisel3] object cloneSupertype { } } +// Returns pairs of all fields, element-level and containers, in a Record and their path names +private[chisel3] object getRecursiveFields { + def apply(data: Data, path: String): Seq[(Data, String)] = data match { + case data: Record => + data.elements.map { case (fieldName, fieldData) => + getRecursiveFields(fieldData, s"$path.$fieldName") + }.fold(Seq(data -> path)) { + _ ++ _ + } + case data: Vec[_] => + data.getElements.zipWithIndex.map { case (fieldData, fieldIndex) => + getRecursiveFields(fieldData, path = s"$path($fieldIndex)") + }.fold(Seq(data -> path)) { + _ ++ _ + } + case data: Element => Seq(data -> path) + } + + def lazily(data: Data, path: String): Seq[(Data, String)] = data match { + case data: Record => + LazyList(data -> path) ++ + data.elements.view.flatMap { case (fieldName, fieldData) => + getRecursiveFields(fieldData, s"$path.$fieldName") + } + case data: Vec[_] => + LazyList(data -> path) ++ + data.getElements.view.zipWithIndex.flatMap { case (fieldData, fieldIndex) => + getRecursiveFields(fieldData, path = s"$path($fieldIndex)") + } + case data: Element => LazyList(data -> path) + } +} + +// Returns pairs of corresponding fields between two Records of the same type +// TODO it seems wrong that Elements are checked for typeEquivalence in Bundle and Vec lit creation +private[chisel3] object getMatchedFields { + def apply(x: Data, y: Data): Seq[(Data, Data)] = (x, y) match { + case (x: Element, y: Element) => + require(x typeEquivalent y) + Seq(x -> y) + case (x: Record, y: Record) => + (x.elements zip y.elements).map { case ((xName, xElt), (yName, yElt)) => + require(xName == yName) // assume fields returned in same, deterministic order + getMatchedFields(xElt, yElt) + }.fold(Seq(x -> y)) { + _ ++ _ + } + case (x: Vec[_], y: Vec[_]) => + (x.getElements zip y.getElements).map { case (xElt, yElt) => + getMatchedFields(xElt, yElt) + }.fold(Seq(x -> y)) { + _ ++ _ + } + } +} + /** Returns the chisel type of a hardware object, allowing other hardware to be constructed from it. */ object chiselTypeOf { @@ -488,6 +547,14 @@ abstract class Data extends HasId with NamedComponent with SourceInfoDoc { } requireIsHardware(this) topBindingOpt match { + // DataView + case Some(ViewBinding(target)) => reify(target).ref + case Some(AggregateViewBinding(viewMap, _)) => + viewMap.get(this) match { + case None => materializeWire() // FIXME FIRRTL doesn't have Aggregate Init expressions + // This should not be possible because Element does the lookup in .topBindingOpt + case x: Some[_] => throwException(s"Internal Error: In .ref for $this got '$topBindingOpt' and '$x'") + } // Literals case Some(ElementLitBinding(litArg)) => litArg case Some(BundleLitBinding(litMap)) => @@ -514,6 +581,20 @@ abstract class Data extends HasId with NamedComponent with SourceInfoDoc { } } + + // Recursively set the parent of the start Data and any children (eg. in an Aggregate) + private[chisel3] def setAllParents(parent: Option[BaseModule]): Unit = { + def rec(data: Data): Unit = { + data._parent = parent + data match { + case _: Element => + case agg: Aggregate => + agg.getElements.foreach(rec) + } + } + rec(this) + } + private[chisel3] def width: Width private[chisel3] def legacyConnect(that: Data)(implicit sourceInfo: SourceInfo): Unit diff --git a/core/src/main/scala/chisel3/Element.scala b/core/src/main/scala/chisel3/Element.scala index 40291b12..bc006922 100644 --- a/core/src/main/scala/chisel3/Element.scala +++ b/core/src/main/scala/chisel3/Element.scala @@ -34,6 +34,10 @@ abstract class Element extends Data { case Some(litArg) => Some(ElementLitBinding(litArg)) case _ => Some(DontCareBinding()) } + case Some(b @ AggregateViewBinding(viewMap, _)) => viewMap.get(this) match { + case Some(elt) => Some(ViewBinding(elt)) + case _ => throwException(s"Internal Error! $this missing from topBinding $b") + } case topBindingOpt => topBindingOpt } diff --git a/core/src/main/scala/chisel3/Module.scala b/core/src/main/scala/chisel3/Module.scala index 41fe4554..64065ec9 100644 --- a/core/src/main/scala/chisel3/Module.scala +++ b/core/src/main/scala/chisel3/Module.scala @@ -184,7 +184,7 @@ package internal { object BaseModule { // Private internal class to serve as a _parent for Data in cloned ports - private[chisel3] class ModuleClone(_proto: BaseModule) extends BaseModule { + private[chisel3] class ModuleClone(_proto: BaseModule) extends PseudoModule { // ClonePorts that hold the bound ports for this module // Used for setting the refs of both this module and the Record private[BaseModule] var _portsRecord: Record = _ @@ -195,7 +195,7 @@ package internal { _component = _proto._component None } - // This module doesn't acutally exist in the FIRRTL so no initialization to do + // This module doesn't actually exist in the FIRRTL so no initialization to do private[chisel3] def initializeInParent(parentCompileOptions: CompileOptions): Unit = () override def desiredName: String = _proto.name @@ -226,19 +226,6 @@ package internal { override def cloneType = (new ClonePorts(elts: _*)).asInstanceOf[this.type] } - // Recursively set the parent of the start Data and any children (eg. in an Aggregate) - private def setAllParents(start: Data, parent: Option[BaseModule]): Unit = { - def rec(data: Data): Unit = { - data._parent = parent - data match { - case _: Element => - case agg: Aggregate => - agg.getElements.foreach(rec) - } - } - rec(start) - } - private[chisel3] def cloneIORecord(proto: BaseModule)(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): ClonePorts = { require(proto.isClosed, "Can't clone a module before module close") // Fake Module to serve as the _parent of the cloned ports @@ -249,7 +236,7 @@ package internal { // currentModule (and not clonePorts) val clonePorts = new ClonePorts(proto.getModulePorts: _*) clonePorts.bind(PortBinding(cloneParent)) - setAllParents(clonePorts, Some(cloneParent)) + clonePorts.setAllParents(Some(cloneParent)) cloneParent._portsRecord = clonePorts // Normally handled during Module construction but ClonePorts really lives in its parent's parent if (!compileOptions.explicitInvalidate) { @@ -303,7 +290,15 @@ package experimental { } } - protected def getIds = { + // Returns the last id contained within a Module + private[chisel3] def _lastId: Long = _ids.last match { + case mod: BaseModule => mod._lastId + case _ => + // Ideally we could just take last._id, but Records store and thus bind their Data in reverse order + _ids.maxBy(_._id)._id + } + + private[chisel3] def getIds = { require(_closed, "Can't get ids before module close") _ids.toSeq } @@ -368,10 +363,10 @@ package experimental { /** Legalized name of this module. */ final lazy val name = try { - // ModuleAspects and ModuleClones are not "true modules" and thus should share + // PseudoModules are not "true modules" and thus should share // their original modules names without uniquification this match { - case (_: ModuleAspect | _: internal.BaseModule.ModuleClone) => desiredName + case _: PseudoModule => desiredName case _ => Builder.globalNamespace.name(desiredName) } } catch { @@ -399,7 +394,14 @@ package experimental { final def toAbsoluteTarget: IsModule = { _parent match { case Some(parent) => parent.toAbsoluteTarget.instOf(this.instanceName, toTarget.module) - case None => toTarget + case None => + // FIXME Special handling for Views - evidence of "weirdness" of .toAbsoluteTarget + // In theory, .toAbsoluteTarget should not be necessary, .toTarget combined with the + // target disambiguation in FIRRTL's deduplication transform should ensure that .toTarget + // is always unambigous. However, legacy workarounds for Chisel's lack of an instance API + // have lead some to use .toAbsoluteTarget as a workaround. A proper instance API will make + // it possible to deprecate and remove .toAbsoluteTarget + if (this == ViewParent) ViewParent.absoluteTarget else toTarget } } diff --git a/core/src/main/scala/chisel3/ModuleAspect.scala b/core/src/main/scala/chisel3/ModuleAspect.scala index 4e37ab35..a528fa72 100644 --- a/core/src/main/scala/chisel3/ModuleAspect.scala +++ b/core/src/main/scala/chisel3/ModuleAspect.scala @@ -2,7 +2,7 @@ package chisel3 -import chisel3.internal.Builder +import chisel3.internal.{Builder, PseudoModule} /** Used by Chisel Aspects to inject Chisel code into modules, after they have been elaborated. * This is an internal API - don't use! @@ -13,7 +13,7 @@ import chisel3.internal.Builder * @param moduleCompileOptions */ abstract class ModuleAspect private[chisel3] (module: RawModule) - (implicit moduleCompileOptions: CompileOptions) extends RawModule { + (implicit moduleCompileOptions: CompileOptions) extends RawModule with PseudoModule { Builder.addAspect(module, this) diff --git a/core/src/main/scala/chisel3/RawModule.scala b/core/src/main/scala/chisel3/RawModule.scala index fadb8dae..74e9db6c 100644 --- a/core/src/main/scala/chisel3/RawModule.scala +++ b/core/src/main/scala/chisel3/RawModule.scala @@ -11,6 +11,7 @@ import chisel3.internal.BaseModule.ModuleClone import chisel3.internal.Builder._ import chisel3.internal.firrtl._ import chisel3.internal.sourceinfo.UnlocatableSourceInfo +import _root_.firrtl.annotations.{IsModule, ModuleTarget} /** Abstract base class for Modules that contain Chisel RTL. * This abstract base class is a user-defined module which does not include implicit clock and reset and supports @@ -157,6 +158,9 @@ trait RequireSyncReset extends Module { package object internal { + /** Marker trait for modules that are not true modules */ + private[chisel3] trait PseudoModule extends BaseModule + // Private reflective version of "val io" to maintain Chisel.Module semantics without having // io as a virtual method. See https://github.com/freechipsproject/chisel3/pull/1550 for more // information about the removal of "val io" @@ -264,4 +268,31 @@ package object internal { } } } + + /** Internal API for [[ViewParent]] */ + sealed private[chisel3] class ViewParentAPI extends RawModule()(ExplicitCompileOptions.Strict) with PseudoModule { + // We must provide `absoluteTarget` but not `toTarget` because otherwise they would be exactly + // the same and we'd have no way to distinguish the kind of target when renaming view targets in + // the Converter + // Note that this is not overriding .toAbsoluteTarget, that is a final def in BaseModule that delegates + // to this method + private[chisel3] val absoluteTarget: IsModule = ModuleTarget(this.circuitName, "_$$AbsoluteView$$_") + + // This module is not instantiable + override private[chisel3] def generateComponent(): Option[Component] = None + override private[chisel3] def initializeInParent(parentCompileOptions: CompileOptions): Unit = () + // This module is not really part of the circuit + _parent = None + + // Sigil to mark views, starts with '_' to make it a legal FIRRTL target + override def desiredName = "_$$View$$_" + + private[chisel3] val fakeComponent: Component = DefModule(this, desiredName, Nil, Nil) + } + + /** Special internal object representing the parent of all views + * + * @note this is a val instead of an object because of the need to wrap in Module(...) + */ + private[chisel3] val ViewParent = Module.do_apply(new ViewParentAPI)(UnlocatableSourceInfo, ExplicitCompileOptions.Strict) } diff --git a/core/src/main/scala/chisel3/experimental/dataview/DataProduct.scala b/core/src/main/scala/chisel3/experimental/dataview/DataProduct.scala new file mode 100644 index 00000000..55dd8505 --- /dev/null +++ b/core/src/main/scala/chisel3/experimental/dataview/DataProduct.scala @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: Apache-2.0 + +package chisel3.experimental.dataview + +import chisel3.experimental.BaseModule +import chisel3.{Data, getRecursiveFields} + +import scala.annotation.implicitNotFound + +/** Typeclass interface for getting elements of type [[Data]] + * + * This is needed for validating [[DataView]]s targeting type `A`. + * Can be thought of as "can be the Target of a DataView". + * + * Chisel provides some implementations in [[DataProduct$ object DataProduct]] that are available + * by default in the implicit scope. + * + * @tparam A Type that has elements of type [[Data]] + * @see [[https://www.chisel-lang.org/chisel3/docs/explanations/dataview#dataproduct Detailed Documentation]] + */ +@implicitNotFound("Could not find implicit value for DataProduct[${A}].\n" + + "Please see https://www.chisel-lang.org/chisel3/docs/explanations/dataview#dataproduct") +trait DataProduct[-A] { + /** Provides [[Data]] elements within some containing object + * + * @param a Containing object + * @param path Hierarchical path to current signal (for error reporting) + * @return Data elements and associated String paths (Strings for error reporting only!) + */ + def dataIterator(a: A, path: String): Iterator[(Data, String)] + + /** Returns a checker to test if the containing object contains a `Data` object + * @note Implementers may want to override if iterating on all `Data` is expensive for `A` and `A` + * will primarily be used in `PartialDataViews` + * @note The returned value is a function, not a true Set, but is describing the functionality of + * Set containment + * @param a Containing object + * @return A checker that itself returns True if a given `Data` is contained in `a` + * as determined by an `==` test + */ + def dataSet(a: A): Data => Boolean = dataIterator(a, "").map(_._1).toSet +} + +/** Encapsulating object for automatically provided implementations of [[DataProduct]] + * + * @note DataProduct implementations provided in this object are available in the implicit scope + */ +object DataProduct { + /** [[DataProduct]] implementation for [[Data]] */ + implicit val dataDataProduct: DataProduct[Data] = new DataProduct[Data] { + def dataIterator(a: Data, path: String): Iterator[(Data, String)] = + getRecursiveFields.lazily(a, path).iterator + } + + /** [[DataProduct]] implementation for [[BaseModule]] */ + implicit val userModuleDataProduct: DataProduct[BaseModule] = new DataProduct[BaseModule] { + def dataIterator(a: BaseModule, path: String): Iterator[(Data, String)] = { + a.getIds.iterator.flatMap { + case d: Data if d.getOptionRef.isDefined => // Using ref to decide if it's truly hardware in the module + Seq(d -> s"${path}.${d.instanceName}") + case b: BaseModule => dataIterator(b, s"$path.${b.instanceName}") + case _ => Seq.empty + } + } + // Overridden for performance + override def dataSet(a: BaseModule): Data => Boolean = { + val lastId = a._lastId // Not cheap to compute + // Return a function + e => e._id > a._id && e._id <= lastId + } + } +} diff --git a/core/src/main/scala/chisel3/experimental/dataview/DataView.scala b/core/src/main/scala/chisel3/experimental/dataview/DataView.scala new file mode 100644 index 00000000..caf004c2 --- /dev/null +++ b/core/src/main/scala/chisel3/experimental/dataview/DataView.scala @@ -0,0 +1,154 @@ +// SPDX-License-Identifier: Apache-2.0 + +package chisel3.experimental.dataview + +import chisel3._ +import chisel3.internal.sourceinfo.SourceInfo +import scala.reflect.runtime.universe.WeakTypeTag + +import annotation.implicitNotFound + + +/** Mapping between a target type `T` and a view type `V` + * + * Enables calling `.viewAs[T]` on instances of the target type. + * + * ==Detailed documentation== + * - [[https://www.chisel-lang.org/chisel3/docs/explanations/dataview Explanation]] + * - [[https://www.chisel-lang.org/chisel3/docs/cookbooks/dataview Cookbook]] + * + * @example {{{ + * class Foo(val w: Int) extends Bundle { + * val a = UInt(w.W) + * } + * class Bar(val w: Int) extends Bundle { + * val b = UInt(w.W) + * } + * // DataViews are created using factory methods in the companion object + * implicit val view = DataView[Foo, Bar]( + * // The first argument is a function constructing a Foo from a Bar + * foo => new Bar(foo.w) + * // The remaining arguments are a variable number of field pairings + * _.a -> _.b + * ) + * }}} + * + * @tparam T Target type (must have an implementation of [[DataProduct]]) + * @tparam V View type + * @see [[DataView$ object DataView]] for factory methods + * @see [[PartialDataView object PartialDataView]] for defining non-total `DataViews` + */ +@implicitNotFound("Could not find implicit value for DataView[${T}, ${V}].\n" + + "Please see https://www.chisel-lang.org/chisel3/docs/explanations/dataview") +sealed class DataView[T : DataProduct, V <: Data] private[chisel3] ( + /** Function constructing an object of the View type from an object of the Target type */ + private[chisel3] val mkView: T => V, + /** Function that returns corresponding fields of the target and view */ + private[chisel3] val mapping: (T, V) => Iterable[(Data, Data)], + // Aliasing this with a def below to make the ScalaDoc show up for the field + _total: Boolean +)( + implicit private[chisel3] val sourceInfo: SourceInfo +) { + /** Indicates if the mapping contains every field of the target */ + def total: Boolean = _total + + override def toString: String = { + val base = sourceInfo.makeMessage(x => x) + val loc = if (base.nonEmpty) base else "@unknown" + val name = if (total) "DataView" else "PartialDataView" + s"$name(defined $loc)" + } + + /** Compose two `DataViews` together to construct a view from the target of this `DataView` to the + * view type of the second `DataView` + * + * @param g a DataView from `V` to new view-type `V2` + * @tparam V2 View type of `DataView` `g` + * @return a new `DataView` from the original `T` to new view-type `V2` + */ + def andThen[V2 <: Data](g: DataView[V, V2])(implicit sourceInfo: SourceInfo): DataView[T, V2] = { + val self = this + // We have to pass the DataProducts and DataViews manually to .viewAs below + val tdp = implicitly[DataProduct[T]] + val vdp = implicitly[DataProduct[V]] + new DataView[T, V2]( + t => g.mkView(mkView(t)), + { case (t, v2) => List(t.viewAs[V](tdp, self).viewAs[V2](vdp, g) -> v2) }, + this.total && g.total + ) { + override def toString: String = s"$self andThen $g" + } + } +} + +/** Factory methods for constructing [[DataView]]s, see class for example use */ +object DataView { + + /** Default factory method, alias for [[pairs]] */ + def apply[T : DataProduct, V <: Data](mkView: T => V, pairs: ((T, V) => (Data, Data))*)(implicit sourceInfo: SourceInfo): DataView[T, V] = + DataView.pairs(mkView, pairs: _*) + + /** Construct [[DataView]]s with pairs of functions from the target and view to corresponding fields */ + def pairs[T : DataProduct, V <: Data](mkView: T => V, pairs: ((T, V) => (Data, Data))*)(implicit sourceInfo: SourceInfo): DataView[T, V] = + mapping(mkView: T => V, swizzle(pairs)) + + /** More general factory method for complex mappings */ + def mapping[T : DataProduct, V <: Data](mkView: T => V, mapping: (T, V) => Iterable[(Data, Data)])(implicit sourceInfo: SourceInfo): DataView[T, V] = + new DataView[T, V](mkView, mapping, _total = true) + + /** Provides `invert` for invertible [[DataView]]s + * + * This must be done as an extension method because it applies an addition constraint on the `Target` + * type parameter, namely that it must be a subtype of [[Data]]. + * + * @note [[PartialDataView]]s are **not** invertible and will result in an elaboration time exception + */ + implicit class InvertibleDataView[T <: Data : WeakTypeTag, V <: Data : WeakTypeTag](view: DataView[T, V]) { + def invert(mkView: V => T): DataView[V, T] = { + // It would've been nice to make this a compiler error, but it's unclear how to make that work. + // We tried having separate TotalDataView and PartialDataView and only defining inversion for + // TotalDataView. For some reason, implicit resolution wouldn't invert TotalDataViews. This is + // probably because it was looking for the super-type DataView and since invertDataView was + // only defined on TotalDataView, it wasn't included in implicit resolution. Thus we end up + // with a runtime check. + if (!view.total) { + val tt = implicitly[WeakTypeTag[T]].tpe + val vv = implicitly[WeakTypeTag[V]].tpe + val msg = s"Cannot invert '$view' as it is non-total.\n Try providing a DataView[$vv, $tt]." + + s"\n Please see https://www.chisel-lang.org/chisel3/docs/explanations/dataview." + throw InvalidViewException(msg) + } + implicit val sourceInfo = view.sourceInfo + new DataView[V, T](mkView, swapArgs(view.mapping), view.total) + } + } + + private[dataview] def swizzle[A, B, C, D](fs: Iterable[(A, B) => (C, D)]): (A, B) => Iterable[(C, D)] = { + case (a, b) => fs.map(f => f(a, b)) + } + + private def swapArgs[A, B, C, D](f: (A, B) => Iterable[(C, D)]): (B, A) => Iterable[(D, C)] = { + case (b, a) => f(a, b).map(_.swap) + } + + /** All Chisel Data are viewable as their own type */ + implicit def identityView[A <: Data](implicit sourceInfo: SourceInfo): DataView[A, A] = + DataView[A, A](chiselTypeOf.apply, { case (x, y) => (x, y) }) +} + +/** Factory methods for constructing non-total [[DataView]]s */ +object PartialDataView { + + /** Default factory method, alias for [[pairs]] */ + def apply[T: DataProduct, V <: Data](mkView: T => V, pairs: ((T, V) => (Data, Data))*)(implicit sourceInfo: SourceInfo): DataView[T, V] = + PartialDataView.pairs(mkView, pairs: _*) + + /** Construct [[DataView]]s with pairs of functions from the target and view to corresponding fields */ + def pairs[T: DataProduct, V <: Data](mkView: T => V, pairs: ((T, V) => (Data, Data))*)(implicit sourceInfo: SourceInfo): DataView[T, V] = + mapping(mkView, DataView.swizzle(pairs)) + + /** More general factory method for complex mappings */ + def mapping[T: DataProduct, V <: Data](mkView: T => V, mapping: (T, V) => Iterable[(Data, Data)])(implicit sourceInfo: SourceInfo): DataView[T, V] = + new DataView[T, V](mkView, mapping, _total = false) +} diff --git a/core/src/main/scala/chisel3/experimental/dataview/package.scala b/core/src/main/scala/chisel3/experimental/dataview/package.scala new file mode 100644 index 00000000..1acf43e1 --- /dev/null +++ b/core/src/main/scala/chisel3/experimental/dataview/package.scala @@ -0,0 +1,251 @@ +// SPDX-License-Identifier: Apache-2.0 + +package chisel3.experimental + +import chisel3._ +import chisel3.internal._ +import chisel3.internal.sourceinfo.SourceInfo + +import scala.annotation.{implicitNotFound, tailrec} +import scala.collection.mutable +import scala.collection.immutable.LazyList // Needed for 2.12 alias + +package object dataview { + case class InvalidViewException(message: String) extends ChiselException(message) + + /** Provides `viewAs` for types that have an implementation of [[DataProduct]] + * + * Calling `viewAs` also requires an implementation of [[DataView]] for the target type + */ + implicit class DataViewable[T](target: T) { + def viewAs[V <: Data](implicit dataproduct: DataProduct[T], dataView: DataView[T, V]): V = { + // TODO put a try catch here for ExpectedHardwareException and perhaps others + // It's likely users will accidentally use chiselTypeOf or something that may error, + // The right thing to use is DataMirror...chiselTypeClone because of composition with DataView.andThen + // Another option is that .andThen could give a fake binding making chiselTypeOfs in the user code safe + val result: V = dataView.mkView(target) + requireIsChiselType(result, "viewAs") + + doBind(target, result, dataView) + + // Setting the parent marks these Data as Views + result.setAllParents(Some(ViewParent)) + // The names of views do not matter except for when a view is annotated. For Views that correspond + // To a single Data, we just forward the name of the Target. For Views that correspond to more + // than one Data, we return this assigned name but rename it in the Convert stage + result.forceName(None, "view", Builder.viewNamespace) + result + } + } + + // This private type alias lets us provide a custom error message for misuing the .viewAs for upcasting Bundles + @implicitNotFound("${A} is not a subtype of ${B}! Did you mean .viewAs[${B}]? " + + "Please see https://www.chisel-lang.org/chisel3/docs/cookbooks/dataview") + private type SubTypeOf[A, B] = A <:< B + + /** Provides `viewAsSupertype` for subclasses of [[Bundle]] */ + implicit class BundleUpcastable[T <: Bundle](target: T) { + /** View a [[Bundle]] or [[Record]] as a parent type (upcast) */ + def viewAsSupertype[V <: Bundle](proto: V)(implicit ev: SubTypeOf[T, V], sourceInfo: SourceInfo): V = { + implicit val dataView = PartialDataView.mapping[T, V](_ => proto, { + case (a, b) => + val aElts = a.elements + val bElts = b.elements + val bKeys = bElts.keySet + val keys = aElts.keysIterator.filter(bKeys.contains) + keys.map(k => aElts(k) -> bElts(k)).toSeq + }) + target.viewAs[V] + } + } + + private def nonTotalViewException(dataView: DataView[_, _], target: Any, view: Data, targetFields: Seq[String], viewFields: Seq[String]) = { + def missingMsg(name: String, fields: Seq[String]): Option[String] = { + val str = fields.mkString(", ") + fields.size match { + case 0 => None + case 1 => Some(s"$name field '$str' is missing") + case _ => Some(s"$name fields '$str' are missing") + } + } + val vs = missingMsg("view", viewFields) + val ts = missingMsg("target", targetFields) + val reasons = (ts ++ vs).mkString(" and ").capitalize + val suggestion = if (ts.nonEmpty) "\n If the view *should* be non-total, try a 'PartialDataView'." else "" + val msg = s"Viewing $target as $view is non-Total!\n $reasons.\n DataView used is $dataView.$suggestion" + throw InvalidViewException(msg) + } + + // TODO should this be moved to class Aggregate / can it be unified with Aggregate.bind? + private def doBind[T : DataProduct, V <: Data](target: T, view: V, dataView: DataView[T, V]): Unit = { + val mapping = dataView.mapping(target, view) + val total = dataView.total + // Lookups to check the mapping results + val viewFieldLookup: Map[Data, String] = getRecursiveFields(view, "_").toMap + val targetContains: Data => Boolean = implicitly[DataProduct[T]].dataSet(target) + + // Resulting bindings for each Element of the View + val childBindings = + new mutable.HashMap[Data, mutable.ListBuffer[Element]] ++ + viewFieldLookup.view + .collect { case (elt: Element, _) => elt } + .map(_ -> new mutable.ListBuffer[Element]) + + def viewFieldName(d: Data): String = + viewFieldLookup.get(d).map(_ + " ").getOrElse("") + d.toString + + // Helper for recording the binding of each + def onElt(te: Element, ve: Element): Unit = { + // TODO can/should we aggregate these errors? + def err(name: String, arg: Data) = + throw InvalidViewException(s"View mapping must only contain Elements within the $name, got $arg") + + // The elements may themselves be views, look through the potential chain of views for the Elements + // that are actually members of the target or view + val tex = unfoldView(te).find(targetContains).getOrElse(err("Target", te)) + val vex = unfoldView(ve).find(viewFieldLookup.contains).getOrElse(err("View", ve)) + + if (tex.getClass != vex.getClass) { + val fieldName = viewFieldName(vex) + throw InvalidViewException(s"Field $fieldName specified as view of non-type-equivalent value $tex") + } + // View width must be unknown or match target width + if (vex.widthKnown && vex.width != tex.width) { + def widthAsString(x: Element) = x.widthOption.map("<" + _ + ">").getOrElse("") + val fieldName = viewFieldName(vex) + val vwidth = widthAsString(vex) + val twidth = widthAsString(tex) + throw InvalidViewException(s"View field $fieldName has width ${vwidth} that is incompatible with target value $tex's width ${twidth}") + } + childBindings(vex) += tex + } + + mapping.foreach { + // Special cased because getMatchedFields checks typeEquivalence on Elements (and is used in Aggregate path) + // Also saves object allocations on common case of Elements + case (ae: Element, be: Element) => onElt(ae, be) + + case (aa: Aggregate, ba: Aggregate) => + if (!ba.typeEquivalent(aa)) { + val fieldName = viewFieldLookup(ba) + throw InvalidViewException(s"field $fieldName specified as view of non-type-equivalent value $aa") + } + getMatchedFields(aa, ba).foreach { + case (aelt: Element, belt: Element) => onElt(aelt, belt) + case _ => // Ignore matching of Aggregates + } + } + + // Errors in totality of the View, use var List to keep fast path cheap (no allocation) + var viewNonTotalErrors: List[Data] = Nil + var targetNonTotalErrors: List[String] = Nil + + val targetSeen: Option[mutable.Set[Data]] = if (total) Some(mutable.Set.empty[Data]) else None + + val resultBindings = childBindings.map { case (data, targets) => + val targetsx = targets match { + case collection.Seq(target: Element) => target + case collection.Seq() => + viewNonTotalErrors = data :: viewNonTotalErrors + data.asInstanceOf[Element] // Return the Data itself, will error after this map, cast is safe + case x => + throw InvalidViewException(s"Got $x, expected Seq(_: Direct)") + } + // TODO record and report aliasing errors + targetSeen.foreach(_ += targetsx) + data -> targetsx + }.toMap + + // Check for totality of Target + targetSeen.foreach { seen => + val lookup = implicitly[DataProduct[T]].dataIterator(target, "_") + for (missed <- lookup.collect { case (d: Element, name) if !seen(d) => name }) { + targetNonTotalErrors = missed :: targetNonTotalErrors + } + } + if (viewNonTotalErrors != Nil || targetNonTotalErrors != Nil) { + val viewErrors = viewNonTotalErrors.map(f => viewFieldLookup.getOrElse(f, f.toString)) + nonTotalViewException(dataView, target, view, targetNonTotalErrors, viewErrors) + } + + view match { + case elt: Element => view.bind(ViewBinding(resultBindings(elt))) + case agg: Aggregate => + // We record total Data mappings to provide a better .toTarget + val topt = target match { + case d: Data if total => Some(d) + case _ => + // Record views that don't have the simpler .toTarget for later renaming + Builder.unnamedViews += view + None + } + // TODO We must also record children as unnamed, some could be namable but this requires changes to the Binding + getRecursiveFields.lazily(view, "_").foreach { + case (agg: Aggregate, _) if agg != view => + Builder.unnamedViews += agg + case _ => // Do nothing + } + agg.bind(AggregateViewBinding(resultBindings, topt)) + } + } + + // Traces an Element that may (or may not) be a view until it no longer maps + // Inclusive of the argument + private def unfoldView(elt: Element): LazyList[Element] = { + def rec(e: Element): LazyList[Element] = e.topBindingOpt match { + case Some(ViewBinding(target)) => target #:: rec(target) + case Some(AggregateViewBinding(mapping, _)) => + val target = mapping(e) + target #:: rec(target) + case Some(_) | None => LazyList.empty + } + elt #:: rec(elt) + } + + // Safe for all Data + private[chisel3] def isView(d: Data): Boolean = d._parent.contains(ViewParent) + + /** Turn any [[Element]] that could be a View into a concrete Element + * + * This is the fundamental "unwrapping" or "tracing" primitive operation for handling Views within + * Chisel. + */ + private[chisel3] def reify(elt: Element): Element = + reify(elt, elt.topBinding) + + /** Turn any [[Element]] that could be a View into a concrete Element + * + * This is the fundamental "unwrapping" or "tracing" primitive operation for handling Views within + * Chisel. + */ + @tailrec private[chisel3] def reify(elt: Element, topBinding: TopBinding): Element = + topBinding match { + case ViewBinding(target) => reify(target, elt.topBinding) + case _ => elt + } + + /** Determine the target of a View if it is a single Target + * + * @note An Aggregate may be a view of unrelated [[Data]] (eg. like a Seq or tuple) and thus this + * there is no single Data representing the Target and this function will return None + * @return The single Data target of this view or None if a single Data doesn't exist + */ + private[chisel3] def reifySingleData(data: Data): Option[Data] = { + val candidate: Option[Data] = + data.binding.collect { // First check if this is a total mapping of an Aggregate + case AggregateViewBinding(_, Some(t)) => t + }.orElse { // Otherwise look via top binding + data.topBindingOpt match { + case None => None + case Some(ViewBinding(target)) => Some(target) + case Some(AggregateViewBinding(lookup, _)) => lookup.get(data) + case Some(_) => None + } + } + candidate.flatMap { d => + // Candidate may itself be a view, keep tracing in those cases + if (isView(d)) reifySingleData(d) else Some(d) + } + } + +} diff --git a/core/src/main/scala/chisel3/internal/BiConnect.scala b/core/src/main/scala/chisel3/internal/BiConnect.scala index aa7d7ac3..4a9bb4f5 100644 --- a/core/src/main/scala/chisel3/internal/BiConnect.scala +++ b/core/src/main/scala/chisel3/internal/BiConnect.scala @@ -3,9 +3,11 @@ package chisel3.internal import chisel3._ +import chisel3.experimental.dataview.reify import chisel3.experimental.{Analog, BaseModule, attach} import chisel3.internal.Builder.pushCommand import chisel3.internal.firrtl.{Connect, DefInvalid} + import scala.language.experimental.macros import chisel3.internal.sourceinfo._ @@ -225,8 +227,10 @@ private[chisel3] object BiConnect { // This function checks if element-level connection operation allowed. // Then it either issues it or throws the appropriate exception. - def elemConnect(implicit sourceInfo: SourceInfo, connectCompileOptions: CompileOptions, left: Element, right: Element, context_mod: RawModule): Unit = { + def elemConnect(implicit sourceInfo: SourceInfo, connectCompileOptions: CompileOptions, _left: Element, _right: Element, context_mod: RawModule): Unit = { import BindingDirection.{Internal, Input, Output} // Using extensively so import these + val left = reify(_left) + val right = reify(_right) // If left or right have no location, assume in context module // This can occur if one of them is a literal, unbound will error previously val left_mod: BaseModule = left.topBinding.location.getOrElse(context_mod) diff --git a/core/src/main/scala/chisel3/internal/Binding.scala b/core/src/main/scala/chisel3/internal/Binding.scala index 300803ce..6f4ab4b0 100644 --- a/core/src/main/scala/chisel3/internal/Binding.scala +++ b/core/src/main/scala/chisel3/internal/Binding.scala @@ -120,6 +120,15 @@ case class MemTypeBinding[T <: Data](parent: MemBase[T]) extends Binding { // It is a source (RHS). It may only be connected/applied to sinks. case class DontCareBinding() extends UnconstrainedBinding +// Views currently only support 1:1 Element-level mappings +private[chisel3] case class ViewBinding(target: Element) extends UnconstrainedBinding +/** Binding for Aggregate Views + * @param childMap Mapping from children of this view to each child's target + * @param target Optional Data this Aggregate views if the view is total and the target is a Data + */ +private[chisel3] case class AggregateViewBinding(childMap: Map[Data, Element], target: Option[Data]) extends UnconstrainedBinding + + sealed trait LitBinding extends UnconstrainedBinding with ReadOnlyBinding // Literal binding attached to a element that is not part of a Bundle. case class ElementLitBinding(litArg: LitArg) extends LitBinding diff --git a/core/src/main/scala/chisel3/internal/Builder.scala b/core/src/main/scala/chisel3/internal/Builder.scala index fef12093..ddaedd2e 100644 --- a/core/src/main/scala/chisel3/internal/Builder.scala +++ b/core/src/main/scala/chisel3/internal/Builder.scala @@ -10,7 +10,8 @@ import chisel3.internal.firrtl._ import chisel3.internal.naming._ import _root_.firrtl.annotations.{CircuitName, ComponentName, IsMember, ModuleName, Named, ReferenceTarget} import _root_.firrtl.annotations.AnnotationUtils.validComponentName -import _root_.firrtl.AnnotationSeq +import _root_.firrtl.{AnnotationSeq, RenameMap} +import chisel3.experimental.dataview.{reify, reifySingleData} import chisel3.internal.Builder.Prefix import logger.LazyLogging @@ -215,32 +216,48 @@ private[chisel3] trait HasId extends InstanceId { private[chisel3] def getRef: Arg = _ref.get private[chisel3] def getOptionRef: Option[Arg] = _ref + private def localName(c: Component): String = _ref match { + case Some(arg) => arg fullName c + case None => computeName(None, None).get + } + + // Helper for reifying views if they map to a single Target + private[chisel3] def reifyTarget: Option[Data] = this match { + case d: Data => reifySingleData(d) // Only Data can be views + case bad => throwException(s"This shouldn't be possible - got $bad with ${_parent}") + } + + // Helper for reifying the parent of a view if the view maps to a single Target + private[chisel3] def reifyParent: BaseModule = reifyTarget.flatMap(_._parent).getOrElse(ViewParent) + // Implementation of public methods. def instanceName: String = _parent match { + case Some(ViewParent) => reifyTarget.map(_.instanceName).getOrElse(this.localName(ViewParent.fakeComponent)) case Some(p) => p._component match { - case Some(c) => _ref match { - case Some(arg) => arg fullName c - case None => computeName(None, None).get - } + case Some(c) => localName(c) case None => throwException("signalName/pathName should be called after circuit elaboration") } case None => throwException("this cannot happen") } def pathName: String = _parent match { case None => instanceName + case Some(ViewParent) => s"${reifyParent.pathName}.$instanceName" case Some(p) => s"${p.pathName}.$instanceName" } def parentPathName: String = _parent match { + case Some(ViewParent) => reifyParent.pathName case Some(p) => p.pathName case None => throwException(s"$instanceName doesn't have a parent") } def parentModName: String = _parent match { + case Some(ViewParent) => reifyParent.name case Some(p) => p.name case None => throwException(s"$instanceName doesn't have a parent") } // TODO Should this be public? protected def circuitName: String = _parent match { case None => instanceName + case Some(ViewParent) => reifyParent.circuitName case Some(p) => p.circuitName } @@ -288,8 +305,10 @@ private[chisel3] trait NamedComponent extends HasId { final def toAbsoluteTarget: ReferenceTarget = { val localTarget = toTarget + def makeTarget(p: BaseModule) = p.toAbsoluteTarget.ref(localTarget.ref).copy(component = localTarget.component) _parent match { - case Some(parent) => parent.toAbsoluteTarget.ref(localTarget.ref).copy(component = localTarget.component) + case Some(ViewParent) => makeTarget(reifyParent) + case Some(parent) => makeTarget(parent) case None => localTarget } } @@ -304,6 +323,11 @@ private[chisel3] class ChiselContext() { // Records the different prefixes which have been scoped at this point in time var prefixStack: Prefix = Nil + + // Views belong to a separate namespace (for renaming) + // The namespace outside of Builder context is useless, but it ensures that views can still be created + // and the resulting .toTarget is very clearly useless (_$$View$$_...) + val viewNamespace = Namespace.empty } private[chisel3] class DynamicContext(val annotationSeq: AnnotationSeq) { @@ -319,6 +343,9 @@ private[chisel3] class DynamicContext(val annotationSeq: AnnotationSeq) { */ val aspectModule: mutable.HashMap[BaseModule, BaseModule] = mutable.HashMap.empty[BaseModule, BaseModule] + // Views that do not correspond to a single ReferenceTarget and thus require renaming + val unnamedViews: ArrayBuffer[Data] = ArrayBuffer.empty + // Set by object Module.apply before calling class Module constructor // Used to distinguish between no Module() wrapping, multiple wrappings, and rewrapping var readyForModuleConstr: Boolean = false @@ -370,6 +397,9 @@ private[chisel3] object Builder extends LazyLogging { def annotationSeq: AnnotationSeq = dynamicContext.annotationSeq def namingStack: NamingStack = dynamicContext.namingStack + def unnamedViews: ArrayBuffer[Data] = dynamicContext.unnamedViews + def viewNamespace: Namespace = chiselContext.get.viewNamespace + // Puts a prefix string onto the prefix stack def pushPrefix(d: String): Unit = { val context = chiselContext.get() @@ -403,6 +433,7 @@ private[chisel3] object Builder extends LazyLogging { case PortBinding(mod) if Builder.currentModule.contains(mod) => data.seedOpt case PortBinding(mod) => map2(mod.seedOpt, data.seedOpt)(_ + "_" + _) case (_: LitBinding | _: DontCareBinding) => None + case _ => Some("view_") // TODO implement } id match { case d: Data => recData(d) @@ -646,8 +677,29 @@ private[chisel3] object Builder extends LazyLogging { } } + // Builds a RenameMap for all Views that do not correspond to a single Data + // These Data give a fake ReferenceTarget for .toTarget and .toReferenceTarget that the returned + // RenameMap can split into the constituent parts + private[chisel3] def makeViewRenameMap: RenameMap = { + val renames = RenameMap() + for (view <- unnamedViews) { + val localTarget = view.toTarget + val absTarget = view.toAbsoluteTarget + val elts = getRecursiveFields.lazily(view, "") + .collect { case (elt: Element, _) => elt } + for (elt <- elts) { + val targetOfView = reify(elt) + renames.record(localTarget, targetOfView.toTarget) + renames.record(absTarget, targetOfView.toAbsoluteTarget) + } + } + renames + } + private [chisel3] def build[T <: RawModule](f: => T, dynamicContext: DynamicContext): (Circuit, T) = { dynamicContextVar.withValue(Some(dynamicContext)) { + ViewParent // Must initialize the singleton in a Builder context or weird things can happen + // in tiny designs/testcases that never access anything in chisel3.internal checkScalaVersion() logger.warn("Elaborating design...") val mod = f @@ -655,7 +707,7 @@ private[chisel3] object Builder extends LazyLogging { errors.checkpoint(logger) logger.warn("Done elaborating.") - (Circuit(components.last.name, components.toSeq, annotations.toSeq), mod) + (Circuit(components.last.name, components.toSeq, annotations.toSeq, makeViewRenameMap), mod) } } initializeSingletons() diff --git a/core/src/main/scala/chisel3/internal/MonoConnect.scala b/core/src/main/scala/chisel3/internal/MonoConnect.scala index b979ebae..5cbab329 100644 --- a/core/src/main/scala/chisel3/internal/MonoConnect.scala +++ b/core/src/main/scala/chisel3/internal/MonoConnect.scala @@ -5,7 +5,9 @@ package chisel3.internal import chisel3._ import chisel3.experimental.{Analog, BaseModule, EnumType, FixedPoint, Interval, UnsafeEnum} import chisel3.internal.Builder.pushCommand +import chisel3.experimental.dataview.reify import chisel3.internal.firrtl.{Connect, DefInvalid} + import scala.language.experimental.macros import chisel3.internal.sourceinfo.SourceInfo @@ -188,8 +190,10 @@ private[chisel3] object MonoConnect { // This function checks if element-level connection operation allowed. // Then it either issues it or throws the appropriate exception. - def elemConnect(implicit sourceInfo: SourceInfo, connectCompileOptions: CompileOptions, sink: Element, source: Element, context_mod: RawModule): Unit = { + def elemConnect(implicit sourceInfo: SourceInfo, connectCompileOptions: CompileOptions, _sink: Element, _source: Element, context_mod: RawModule): Unit = { import BindingDirection.{Internal, Input, Output} // Using extensively so import these + val sink = reify(_sink) + val source = reify(_source) // If source has no location, assume in context module // This can occur if is a literal, unbound will error previously val sink_mod: BaseModule = sink.topBinding.location.getOrElse(throw UnwritableSinkException) diff --git a/core/src/main/scala/chisel3/internal/firrtl/IR.scala b/core/src/main/scala/chisel3/internal/firrtl/IR.scala index 5796522c..f8a3cf7f 100644 --- a/core/src/main/scala/chisel3/internal/firrtl/IR.scala +++ b/core/src/main/scala/chisel3/internal/firrtl/IR.scala @@ -8,7 +8,8 @@ import chisel3.internal._ import chisel3.internal.sourceinfo.SourceInfo import chisel3.experimental._ import _root_.firrtl.{ir => firrtlir} -import _root_.firrtl.PrimOps +import _root_.firrtl.{PrimOps, RenameMap} +import _root_.firrtl.annotations.Annotation import scala.collection.immutable.NumericRange import scala.math.BigDecimal.RoundingMode @@ -789,4 +790,6 @@ abstract class Component extends Arg { case class DefModule(id: RawModule, name: String, ports: Seq[Port], commands: Seq[Command]) extends Component case class DefBlackBox(id: BaseBlackBox, name: String, ports: Seq[Port], topDir: SpecifiedDirection, params: Map[String, Param]) extends Component -case class Circuit(name: String, components: Seq[Component], annotations: Seq[ChiselAnnotation] = Seq.empty) +case class Circuit(name: String, components: Seq[Component], annotations: Seq[ChiselAnnotation], renames: RenameMap) { + def firrtlAnnotations: Iterable[Annotation] = annotations.flatMap(_.toFirrtl.update(renames)) +} -- cgit v1.2.3 From ed894c61474c8bc73761a6c360ef9d14505d853b Mon Sep 17 00:00:00 2001 From: Jiuyang Liu Date: Wed, 18 Aug 2021 03:44:17 +0800 Subject: remove DefRegInit, change DefReg API with option definition. (#1944) * remove DefRegInit, change DefReg API with option defination. * add error message * use Option[RegInitIR]. Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>--- core/src/main/scala/chisel3/Reg.scala | 4 ++-- core/src/main/scala/chisel3/internal/firrtl/Converter.scala | 4 ++-- core/src/main/scala/chisel3/internal/firrtl/IR.scala | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) (limited to 'core/src') diff --git a/core/src/main/scala/chisel3/Reg.scala b/core/src/main/scala/chisel3/Reg.scala index bd9e5311..9cdbf6a1 100644 --- a/core/src/main/scala/chisel3/Reg.scala +++ b/core/src/main/scala/chisel3/Reg.scala @@ -42,7 +42,7 @@ object Reg { val clock = Node(Builder.forcedClock) reg.bind(RegBinding(Builder.forcedUserModule, Builder.currentWhen())) - pushCommand(DefReg(sourceInfo, reg, clock)) + pushCommand(DefReg(sourceInfo, reg, clock, None)) reg } @@ -176,7 +176,7 @@ object RegInit { reg.bind(RegBinding(Builder.forcedUserModule, Builder.currentWhen())) requireIsHardware(init, "reg initializer") - pushCommand(DefRegInit(sourceInfo, reg, clock.ref, reset.ref, init.ref)) + pushCommand(DefReg(sourceInfo, reg, clock.ref, Some(RegInitIR(reset.ref, init.ref)))) reg } diff --git a/core/src/main/scala/chisel3/internal/firrtl/Converter.scala b/core/src/main/scala/chisel3/internal/firrtl/Converter.scala index 8efb2abc..e8fb197c 100644 --- a/core/src/main/scala/chisel3/internal/firrtl/Converter.scala +++ b/core/src/main/scala/chisel3/internal/firrtl/Converter.scala @@ -117,10 +117,10 @@ private[chisel3] object Converter { Some(fir.DefNode(convert(e.sourceInfo), e.name, expr)) case e @ DefWire(info, id) => Some(fir.DefWire(convert(info), e.name, extractType(id, info))) - case e @ DefReg(info, id, clock) => + case e @ DefReg(info, id, clock, None) => Some(fir.DefRegister(convert(info), e.name, extractType(id, info), convert(clock, ctx, info), firrtl.Utils.zero, convert(getRef(id, info), ctx, info))) - case e @ DefRegInit(info, id, clock, reset, init) => + case e @ DefReg(info, id, clock, Some(RegInitIR(reset, init))) => Some(fir.DefRegister(convert(info), e.name, extractType(id, info), convert(clock, ctx, info), convert(reset, ctx, info), convert(init, ctx, info))) case e @ DefMemory(info, id, t, size) => diff --git a/core/src/main/scala/chisel3/internal/firrtl/IR.scala b/core/src/main/scala/chisel3/internal/firrtl/IR.scala index f8a3cf7f..a45ae3c2 100644 --- a/core/src/main/scala/chisel3/internal/firrtl/IR.scala +++ b/core/src/main/scala/chisel3/internal/firrtl/IR.scala @@ -758,8 +758,8 @@ abstract class Definition extends Command { case class DefPrim[T <: Data](sourceInfo: SourceInfo, id: T, op: PrimOp, args: Arg*) extends Definition case class DefInvalid(sourceInfo: SourceInfo, arg: Arg) extends Command case class DefWire(sourceInfo: SourceInfo, id: Data) extends Definition -case class DefReg(sourceInfo: SourceInfo, id: Data, clock: Arg) extends Definition -case class DefRegInit(sourceInfo: SourceInfo, id: Data, clock: Arg, reset: Arg, init: Arg) extends Definition +case class RegInitIR(reset: Arg, init: Arg) +case class DefReg(sourceInfo: SourceInfo, id: Data, clock: Arg, regInit: Option[RegInitIR]) extends Definition case class DefMemory(sourceInfo: SourceInfo, id: HasId, t: Data, size: BigInt) extends Definition case class DefSeqMemory(sourceInfo: SourceInfo, id: HasId, t: Data, size: BigInt, readUnderWrite: fir.ReadUnderWrite.Value) extends Definition case class DefMemPort[T <: Data](sourceInfo: SourceInfo, id: T, source: Node, dir: MemPortDirection, index: Arg, clock: Arg) extends Definition -- cgit v1.2.3 From 7c8a032e7e23902283035d93579b8dc477b32f6a Mon Sep 17 00:00:00 2001 From: Jack Koenig Date: Tue, 17 Aug 2021 18:22:16 -0700 Subject: Revert "remove DefRegInit, change DefReg API with option definition. (#1944)" (#2080) This reverts commit ed894c61474c8bc73761a6c360ef9d14505d853b.--- core/src/main/scala/chisel3/Reg.scala | 4 ++-- core/src/main/scala/chisel3/internal/firrtl/Converter.scala | 4 ++-- core/src/main/scala/chisel3/internal/firrtl/IR.scala | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) (limited to 'core/src') diff --git a/core/src/main/scala/chisel3/Reg.scala b/core/src/main/scala/chisel3/Reg.scala index 9cdbf6a1..bd9e5311 100644 --- a/core/src/main/scala/chisel3/Reg.scala +++ b/core/src/main/scala/chisel3/Reg.scala @@ -42,7 +42,7 @@ object Reg { val clock = Node(Builder.forcedClock) reg.bind(RegBinding(Builder.forcedUserModule, Builder.currentWhen())) - pushCommand(DefReg(sourceInfo, reg, clock, None)) + pushCommand(DefReg(sourceInfo, reg, clock)) reg } @@ -176,7 +176,7 @@ object RegInit { reg.bind(RegBinding(Builder.forcedUserModule, Builder.currentWhen())) requireIsHardware(init, "reg initializer") - pushCommand(DefReg(sourceInfo, reg, clock.ref, Some(RegInitIR(reset.ref, init.ref)))) + pushCommand(DefRegInit(sourceInfo, reg, clock.ref, reset.ref, init.ref)) reg } diff --git a/core/src/main/scala/chisel3/internal/firrtl/Converter.scala b/core/src/main/scala/chisel3/internal/firrtl/Converter.scala index e8fb197c..8efb2abc 100644 --- a/core/src/main/scala/chisel3/internal/firrtl/Converter.scala +++ b/core/src/main/scala/chisel3/internal/firrtl/Converter.scala @@ -117,10 +117,10 @@ private[chisel3] object Converter { Some(fir.DefNode(convert(e.sourceInfo), e.name, expr)) case e @ DefWire(info, id) => Some(fir.DefWire(convert(info), e.name, extractType(id, info))) - case e @ DefReg(info, id, clock, None) => + case e @ DefReg(info, id, clock) => Some(fir.DefRegister(convert(info), e.name, extractType(id, info), convert(clock, ctx, info), firrtl.Utils.zero, convert(getRef(id, info), ctx, info))) - case e @ DefReg(info, id, clock, Some(RegInitIR(reset, init))) => + case e @ DefRegInit(info, id, clock, reset, init) => Some(fir.DefRegister(convert(info), e.name, extractType(id, info), convert(clock, ctx, info), convert(reset, ctx, info), convert(init, ctx, info))) case e @ DefMemory(info, id, t, size) => diff --git a/core/src/main/scala/chisel3/internal/firrtl/IR.scala b/core/src/main/scala/chisel3/internal/firrtl/IR.scala index a45ae3c2..f8a3cf7f 100644 --- a/core/src/main/scala/chisel3/internal/firrtl/IR.scala +++ b/core/src/main/scala/chisel3/internal/firrtl/IR.scala @@ -758,8 +758,8 @@ abstract class Definition extends Command { case class DefPrim[T <: Data](sourceInfo: SourceInfo, id: T, op: PrimOp, args: Arg*) extends Definition case class DefInvalid(sourceInfo: SourceInfo, arg: Arg) extends Command case class DefWire(sourceInfo: SourceInfo, id: Data) extends Definition -case class RegInitIR(reset: Arg, init: Arg) -case class DefReg(sourceInfo: SourceInfo, id: Data, clock: Arg, regInit: Option[RegInitIR]) extends Definition +case class DefReg(sourceInfo: SourceInfo, id: Data, clock: Arg) extends Definition +case class DefRegInit(sourceInfo: SourceInfo, id: Data, clock: Arg, reset: Arg, init: Arg) extends Definition case class DefMemory(sourceInfo: SourceInfo, id: HasId, t: Data, size: BigInt) extends Definition case class DefSeqMemory(sourceInfo: SourceInfo, id: HasId, t: Data, size: BigInt, readUnderWrite: fir.ReadUnderWrite.Value) extends Definition case class DefMemPort[T <: Data](sourceInfo: SourceInfo, id: T, source: Node, dir: MemPortDirection, index: Arg, clock: Arg) extends Definition -- cgit v1.2.3 From efe448c5ca907b3d7a40407f720aa6d4ff2a1a4e Mon Sep 17 00:00:00 2001 From: Kevin Laeufer Date: Wed, 18 Aug 2021 16:46:03 -0700 Subject: Builder: downgrade "Elaborating design" message to info (#2081) --- core/src/main/scala/chisel3/internal/Builder.scala | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'core/src') diff --git a/core/src/main/scala/chisel3/internal/Builder.scala b/core/src/main/scala/chisel3/internal/Builder.scala index ddaedd2e..f7306d5d 100644 --- a/core/src/main/scala/chisel3/internal/Builder.scala +++ b/core/src/main/scala/chisel3/internal/Builder.scala @@ -701,11 +701,11 @@ private[chisel3] object Builder extends LazyLogging { ViewParent // Must initialize the singleton in a Builder context or weird things can happen // in tiny designs/testcases that never access anything in chisel3.internal checkScalaVersion() - logger.warn("Elaborating design...") + logger.info("Elaborating design...") val mod = f mod.forceName(None, mod.name, globalNamespace) errors.checkpoint(logger) - logger.warn("Done elaborating.") + logger.info("Done elaborating.") (Circuit(components.last.name, components.toSeq, annotations.toSeq, makeViewRenameMap), mod) } -- cgit v1.2.3 From f50ce19406e45982390162777fb62c8563c962c7 Mon Sep 17 00:00:00 2001 From: anniej-sifive Date: Mon, 23 Aug 2021 14:37:09 -0700 Subject: Add multiple dimensions to VecInit fill and iterate (#2065) Co-authored-by: Jack Koenig --- core/src/main/scala/chisel3/Aggregate.scala | 129 +++++++++++++++++++++++++--- 1 file changed, 117 insertions(+), 12 deletions(-) (limited to 'core/src') diff --git a/core/src/main/scala/chisel3/Aggregate.scala b/core/src/main/scala/chisel3/Aggregate.scala index 58bc5ccb..17e46cb3 100644 --- a/core/src/main/scala/chisel3/Aggregate.scala +++ b/core/src/main/scala/chisel3/Aggregate.scala @@ -488,6 +488,21 @@ sealed class Vec[T <: Data] private[chisel3] (gen: => T, val length: Int) } object VecInit extends SourceInfoDoc { + + /** Gets the correct connect operation (directed hardware assign or bulk connect) for element in Vec. + */ + private def getConnectOpFromDirectionality[T <: Data](proto: T)(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): (T, T) => Unit = proto.direction match { + case ActualDirection.Input | ActualDirection.Output | ActualDirection.Unspecified => + // When internal wires are involved, driver / sink must be specified explicitly, otherwise + // the system is unable to infer which is driver / sink + (x, y) => x := y + case ActualDirection.Bidirectional(_) => + // For bidirectional, must issue a bulk connect so subelements are resolved correctly. + // Bulk connecting two wires may not succeed because Chisel frontend does not infer + // directions. + (x, y) => x <> y + } + /** Creates a new [[Vec]] composed of elements of the input Seq of [[Data]] * nodes. * @@ -513,18 +528,10 @@ object VecInit extends SourceInfoDoc { elts.foreach(requireIsHardware(_, "vec element")) val vec = Wire(Vec(elts.length, cloneSupertype(elts, "Vec"))) - - // TODO: try to remove the logic for this mess - elts.head.direction match { - case ActualDirection.Input | ActualDirection.Output | ActualDirection.Unspecified => - // When internal wires are involved, driver / sink must be specified explicitly, otherwise - // the system is unable to infer which is driver / sink - (vec zip elts).foreach(x => x._1 := x._2) - case ActualDirection.Bidirectional(_) => - // For bidirectional, must issue a bulk connect so subelements are resolved correctly. - // Bulk connecting two wires may not succeed because Chisel frontend does not infer - // directions. - (vec zip elts).foreach(x => x._1 <> x._2) + val op = getConnectOpFromDirectionality(vec.head) + + (vec zip elts).foreach{ x => + op(x._1, x._2) } vec } @@ -557,6 +564,73 @@ object VecInit extends SourceInfoDoc { def do_tabulate[T <: Data](n: Int)(gen: (Int) => T)(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Vec[T] = apply((0 until n).map(i => gen(i))) + /** Creates a new 2D [[Vec]] of length `n by m` composed of the results of the given + * function applied over a range of integer values starting from 0. + * + * @param n number of 1D vectors inside outer vector + * @param m number of elements in each 1D vector (the function is applied from + * 0 to `n-1`) + * @param gen function that takes in an Int (the index) and returns a + * [[Data]] that becomes the output element + */ + def tabulate[T <: Data](n: Int, m: Int)(gen: (Int, Int) => T): Vec[Vec[T]] = macro VecTransform.tabulate2D + + /** @group SourceInfoTransformMacro */ + def do_tabulate[T <: Data](n: Int, m: Int)(gen: (Int, Int) => T)(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Vec[Vec[T]] = { + // TODO make this lazy (requires LazyList and cross compilation, beyond the scope of this PR) + val elts = Seq.tabulate(n, m)(gen) + val flatElts = elts.flatten + + require(flatElts.nonEmpty, "Vec hardware values are not allowed to be empty") + flatElts.foreach(requireIsHardware(_, "vec element")) + + val tpe = cloneSupertype(flatElts, "Vec.tabulate") + val myVec = Wire(Vec(n, Vec(m, tpe))) + val op = getConnectOpFromDirectionality(myVec.head.head) + for ( + (xs1D, ys1D) <- myVec zip elts; + (x, y) <- xs1D zip ys1D + ) { + op(x, y) + } + myVec + } + + /** Creates a new 3D [[Vec]] of length `n by m by p` composed of the results of the given + * function applied over a range of integer values starting from 0. + * + * @param n number of 2D vectors inside outer vector + * @param m number of 1D vectors in each 2D vector + * @param p number of elements in each 1D vector + * @param gen function that takes in an Int (the index) and returns a + * [[Data]] that becomes the output element + */ + def tabulate[T <: Data](n: Int, m: Int, p: Int)(gen: (Int, Int, Int) => T): Vec[Vec[Vec[T]]] = macro VecTransform.tabulate3D + + /** @group SourceInfoTransformMacro */ + def do_tabulate[T <: Data](n: Int, m: Int, p: Int)(gen: (Int, Int, Int) => T)(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Vec[Vec[Vec[T]]] = { + // TODO make this lazy (requires LazyList and cross compilation, beyond the scope of this PR) + val elts = Seq.tabulate(n, m, p)(gen) + val flatElts = elts.flatten.flatten + + require(flatElts.nonEmpty, "Vec hardware values are not allowed to be empty") + flatElts.foreach(requireIsHardware(_, "vec element")) + + val tpe = cloneSupertype(flatElts, "Vec.tabulate") + val myVec = Wire(Vec(n, Vec(m, Vec(p, tpe)))) + val op = getConnectOpFromDirectionality(myVec.head.head.head) + + for ( + (xs2D, ys2D) <- myVec zip elts; + (xs1D, ys1D) <- xs2D zip ys2D; + (x, y) <- xs1D zip ys1D + ) { + op(x, y) + } + + myVec + } + /** Creates a new [[Vec]] of length `n` composed of the result of the given * function applied to an element of data type T. * @@ -570,6 +644,37 @@ object VecInit extends SourceInfoDoc { def do_fill[T <: Data](n: Int)(gen: => T)(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Vec[T] = apply(Seq.fill(n)(gen)) + /** Creates a new 2D [[Vec]] of length `n by m` composed of the result of the given + * function applied to an element of data type T. + * + * @param n number of inner vectors (rows) in the outer vector + * @param m number of elements in each inner vector (column) + * @param gen function that takes in an element T and returns an output + * element of the same type + */ + def fill[T <: Data](n: Int, m: Int)(gen: => T): Vec[Vec[T]] = macro VecTransform.fill2D + + /** @group SourceInfoTransformMacro */ + def do_fill[T <: Data](n: Int, m: Int)(gen: => T)(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Vec[Vec[T]] = { + do_tabulate(n, m)((_, _) => gen) + } + + /** Creates a new 3D [[Vec]] of length `n by m by p` composed of the result of the given + * function applied to an element of data type T. + * + * @param n number of 2D vectors inside outer vector + * @param m number of 1D vectors in each 2D vector + * @param p number of elements in each 1D vector + * @param gen function that takes in an element T and returns an output + * element of the same type + */ + def fill[T <: Data](n: Int, m: Int, p: Int)(gen: => T): Vec[Vec[Vec[T]]] = macro VecTransform.fill3D + + /** @group SourceInfoTransformMacro */ + def do_fill[T <: Data](n: Int, m: Int, p: Int)(gen: => T)(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Vec[Vec[Vec[T]]] = { + do_tabulate(n, m, p)((_, _, _) => gen) + } + /** Creates a new [[Vec]] of length `n` composed of the result of the given * function applied to an element of data type T. * -- cgit v1.2.3 From 73bd4ee6b9b510725b692c33e075362a19512d2c Mon Sep 17 00:00:00 2001 From: Jack Koenig Date: Fri, 20 Aug 2021 11:30:27 -0700 Subject: Remove chisel3's own firrtl Emitter, use firrtl Serializer This will be slightly slower as it involves converting from Chisel modules to FIRRTL modules before turning them into Strings. This cost is somewhat mitigated by doing that conversion lazily such that we never materialize the entire firrtl Circuit in memory, only 1 module at a time. --- core/src/main/scala/chisel3/internal/firrtl/Converter.scala | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'core/src') diff --git a/core/src/main/scala/chisel3/internal/firrtl/Converter.scala b/core/src/main/scala/chisel3/internal/firrtl/Converter.scala index 8efb2abc..f56c3b15 100644 --- a/core/src/main/scala/chisel3/internal/firrtl/Converter.scala +++ b/core/src/main/scala/chisel3/internal/firrtl/Converter.scala @@ -9,6 +9,7 @@ import chisel3.internal.{HasId, castToInt, throwException} import scala.annotation.tailrec import scala.collection.immutable.Queue +import scala.collection.immutable.LazyList // Needed for 2.12 alias private[chisel3] object Converter { // TODO modeled on unpack method on Printable, refactor? @@ -301,5 +302,11 @@ private[chisel3] object Converter { def convert(circuit: Circuit): fir.Circuit = fir.Circuit(fir.NoInfo, circuit.components.map(convert), circuit.name) + + // TODO Unclear if this should just be the default + def convertLazily(circuit: Circuit): fir.Circuit = { + val lazyModules = LazyList() ++ circuit.components + fir.Circuit(fir.NoInfo, lazyModules.map(convert), circuit.name) + } } -- cgit v1.2.3 From 29665743acff120bc87ee997890d7f952317144e Mon Sep 17 00:00:00 2001 From: Kevin Laeufer Date: Mon, 30 Aug 2021 16:06:59 -0700 Subject: SyncReadMem: fix bug with read(addr) and add some formal tests (#2092) --- core/src/main/scala/chisel3/Mem.scala | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) (limited to 'core/src') diff --git a/core/src/main/scala/chisel3/Mem.scala b/core/src/main/scala/chisel3/Mem.scala index 90525bfa..183620b6 100644 --- a/core/src/main/scala/chisel3/Mem.scala +++ b/core/src/main/scala/chisel3/Mem.scala @@ -213,8 +213,14 @@ sealed class SyncReadMem[T <: Data] private (t: T, n: BigInt, val readUnderWrite var port: Option[T] = None when (enable) { a := addr - port = Some(read(a)) + port = Some(super.do_read(a)) } port.get } + + /** @group SourceInfoTransformMacro*/ + override def do_read(idx: UInt)(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions) = + do_read(addr = idx, enable = true.B) + // note: we implement do_read(addr) for SyncReadMem in terms of do_read(addr, en) in order to ensure that + // `mem.read(addr)` will always behave the same as `mem.read(addr, true.B)` } -- cgit v1.2.3 From 7fb2c1ebc23ca07e5de6416a284e1be1b62a48ac Mon Sep 17 00:00:00 2001 From: Jack Koenig Date: Mon, 30 Aug 2021 18:56:33 -0700 Subject: Fix chisel3 <> for compatibility Bundles (Take 3) (#2093) Previous incomplete fixes in #2023 and #2031. The legality of a FIRRTL connection is determined by type and flow. Chisel does not have access to true flow information. Previous fix attempts tried to use ActualDirection as a stand-in for flow, but it is incorrect in many cases. This new approach checks the flows of the lvalue and rvalues in the connect and flips the connection if either the lvalue cannot be a sink or the rvalue cannot be a source.--- .../main/scala/chisel3/internal/BiConnect.scala | 27 +++++++++++++++------- 1 file changed, 19 insertions(+), 8 deletions(-) (limited to 'core/src') diff --git a/core/src/main/scala/chisel3/internal/BiConnect.scala b/core/src/main/scala/chisel3/internal/BiConnect.scala index 4a9bb4f5..aa58cb95 100644 --- a/core/src/main/scala/chisel3/internal/BiConnect.scala +++ b/core/src/main/scala/chisel3/internal/BiConnect.scala @@ -11,6 +11,8 @@ import chisel3.internal.firrtl.{Connect, DefInvalid} import scala.language.experimental.macros import chisel3.internal.sourceinfo._ +import scala.annotation.tailrec + /** * BiConnect.connect executes a bidirectional connection element-wise. * @@ -120,15 +122,24 @@ private[chisel3] object BiConnect { val notStrict = Seq(left_r.compileOptions, right_r.compileOptions).contains(ExplicitCompileOptions.NotStrict) if (notStrict) { - // chisel3 <> is commutative but FIRRTL <- is not - val flipped = { - import ActualDirection._ - // Everything is flipped when it's the port of a child - val childPort = left_r._parent.get != context_mod - val isFlipped = Seq(Bidirectional(Flipped), Input).contains(left_r.direction) - isFlipped ^ childPort + // Traces flow from a child Data to its parent + @tailrec def traceFlow(currentlyFlipped: Boolean, data: Data): Boolean = { + import SpecifiedDirection.{Input => SInput, Flip => SFlip} + val sdir = data.specifiedDirection + val flipped = sdir == SInput || sdir == SFlip + data.binding.get match { + case ChildBinding(parent) => traceFlow(flipped ^ currentlyFlipped, parent) + case PortBinding(enclosure) => + val childPort = enclosure != context_mod + childPort ^ flipped ^ currentlyFlipped + case _ => true + } } - val (newLeft, newRight) = if (flipped) pair.swap else pair + def canBeSink(data: Data): Boolean = traceFlow(true, data) + def canBeSource(data: Data): Boolean = traceFlow(false, data) + // chisel3 <> is commutative but FIRRTL <- is not + val flipConnection = !canBeSink(left_r) || !canBeSource(right_r) + val (newLeft, newRight) = if (flipConnection) pair.swap else pair newLeft.bulkConnect(newRight)(sourceInfo, ExplicitCompileOptions.NotStrict) } else { recordConnect(sourceInfo, connectCompileOptions, left_r, right_r, context_mod) -- cgit v1.2.3 From 9fa8da227569455a77596355aeb114f9c164510a Mon Sep 17 00:00:00 2001 From: Adam Izraelevitz Date: Sun, 5 Sep 2021 12:11:32 -0700 Subject: Add Definition and Instance API (#2045) This introduces a new experimental API for module instantiation that disentagles elaborating the definition (or implementation) from instantiation of a given module. This solves Chisel's longstanding reliance on "Deduplication" for generating Verilog with multiple instances of the same module. The new API resides in package chisel3.experimental.hierarchy. Please see the hierarchy ScalaDoc, documentation, and tests for examples of use. Co-authored-by: Jack Koenig Co-authored-by: Megan Wachs Co-authored-by: Schuyler Eldridge --- core/src/main/scala/chisel3/BlackBox.scala | 3 +- core/src/main/scala/chisel3/Module.scala | 107 +++++- core/src/main/scala/chisel3/RawModule.scala | 9 +- .../experimental/hierarchy/Definition.scala | 99 ++++++ .../chisel3/experimental/hierarchy/Instance.scala | 111 +++++++ .../experimental/hierarchy/IsInstantiable.scala | 17 + .../experimental/hierarchy/IsLookupable.scala | 25 ++ .../experimental/hierarchy/Lookupable.scala | 368 +++++++++++++++++++++ .../chisel3/experimental/hierarchy/package.scala | 48 +++ core/src/main/scala/chisel3/internal/Binding.scala | 5 + core/src/main/scala/chisel3/internal/Builder.scala | 49 ++- .../main/scala/chisel3/internal/firrtl/IR.scala | 33 +- 12 files changed, 846 insertions(+), 28 deletions(-) create mode 100644 core/src/main/scala/chisel3/experimental/hierarchy/Definition.scala create mode 100644 core/src/main/scala/chisel3/experimental/hierarchy/Instance.scala create mode 100644 core/src/main/scala/chisel3/experimental/hierarchy/IsInstantiable.scala create mode 100644 core/src/main/scala/chisel3/experimental/hierarchy/IsLookupable.scala create mode 100644 core/src/main/scala/chisel3/experimental/hierarchy/Lookupable.scala create mode 100644 core/src/main/scala/chisel3/experimental/hierarchy/package.scala (limited to 'core/src') diff --git a/core/src/main/scala/chisel3/BlackBox.scala b/core/src/main/scala/chisel3/BlackBox.scala index 0c42600f..38b08193 100644 --- a/core/src/main/scala/chisel3/BlackBox.scala +++ b/core/src/main/scala/chisel3/BlackBox.scala @@ -158,11 +158,12 @@ abstract class BlackBox(val params: Map[String, Param] = Map.empty[String, Param val namedPorts = _io.elements.toSeq.reverse // ListMaps are stored in reverse order - // setRef is not called on the actual io. // There is a risk of user improperly attempting to connect directly with io // Long term solution will be to define BlackBox IO differently as part of // it not descending from the (current) Module for ((name, port) <- namedPorts) { + // We are setting a 'fake' ref for io, so that cloneType works but if a user connects to io, it still fails. + this.findPort("io").get.setRef(ModuleIO(internal.ViewParent, ""), force = true) // We have to force override the _ref because it was set during IO binding port.setRef(ModuleIO(this, _namespace.name(name)), force = true) } diff --git a/core/src/main/scala/chisel3/Module.scala b/core/src/main/scala/chisel3/Module.scala index 64065ec9..d0171693 100644 --- a/core/src/main/scala/chisel3/Module.scala +++ b/core/src/main/scala/chisel3/Module.scala @@ -121,7 +121,8 @@ abstract class Module(implicit moduleCompileOptions: CompileOptions) extends Raw private[chisel3] def mkReset: Reset = { // Top module and compatibility mode use Bool for reset - val inferReset = _parent.isDefined && moduleCompileOptions.inferModuleReset + // Note that a Definition elaboration will lack a parent, but still not be a Top module + val inferReset = (_parent.isDefined || Builder.inDefinition) && moduleCompileOptions.inferModuleReset if (inferReset) Reset() else Bool() } @@ -181,13 +182,31 @@ package experimental { package internal { import chisel3.experimental.BaseModule + import chisel3.experimental.hierarchy.IsInstantiable object BaseModule { + /** Represents a clone of an underlying object. This is used to support CloneModuleAsRecord and Instance/Definition. + * + * @note We don't actually "clone" anything in the traditional sense but is a placeholder so we lazily clone internal state + */ + private [chisel3] trait IsClone[+T] { + // Underlying object of which this is a clone of + val _proto: T + def getProto: T = _proto + def isACloneOf(a: Any): Boolean = this == a || _proto == a + } + // Private internal class to serve as a _parent for Data in cloned ports - private[chisel3] class ModuleClone(_proto: BaseModule) extends PseudoModule { + private[chisel3] class ModuleClone[T <: BaseModule] (val _proto: T) extends PseudoModule with IsClone[T] { + override def toString = s"ModuleClone(${_proto})" + def getPorts = _portsRecord // ClonePorts that hold the bound ports for this module // Used for setting the refs of both this module and the Record private[BaseModule] var _portsRecord: Record = _ + // This is necessary for correctly supporting .toTarget on a Module Clone. If it is made from the + // Instance/Definition API, it should return an instanceTarget. If made from CMAR, it should return a + // ModuleTarget. + private[chisel3] var _madeFromDefinition: Boolean = false // Don't generate a component, but point to the one for the cloned Module private[chisel3] def generateComponent(): Option[Component] = { require(!_closed, "Can't generate module more than once") @@ -195,9 +214,15 @@ package internal { _component = _proto._component None } + // Maps proto ports to module clone's ports + private[chisel3] lazy val ioMap: Map[Data, Data] = { + val name2Port = getPorts.elements + _proto.getChiselPorts.map { case (name, data) => data -> name2Port(name) }.toMap + } // This module doesn't actually exist in the FIRRTL so no initialization to do private[chisel3] def initializeInParent(parentCompileOptions: CompileOptions): Unit = () + // Name of this instance's module is the same as the proto's name override def desiredName: String = _proto.name private[chisel3] def setRefAndPortsRef(namespace: Namespace): Unit = { @@ -215,6 +240,53 @@ package internal { } } + /** Represents a module viewed from a different instance context. + * + * @note Why do we need both ModuleClone and InstanceClone? If we are annotating a reference in a module-clone, + * all submodules must be also be 'cloned' so the toTarget can be computed properly. However, we don't need separate + * connectable ports for this instance; all that's different from the proto is the parent. + * + * @note In addition, the instance name of an InstanceClone is going to be the SAME as the proto, but this is not true + * for ModuleClone. + */ + private[chisel3] final class InstanceClone[T <: BaseModule] (val _proto: T, val instName: () => String) extends PseudoModule with IsClone[T] { + override def toString = s"InstanceClone(${_proto})" + // No addition components are generated + private[chisel3] def generateComponent(): Option[Component] = None + // Necessary for toTarget to work + private[chisel3] def setAsInstanceRef(): Unit = { this.setRef(Ref(instName())) } + // This module doesn't acutally exist in the FIRRTL so no initialization to do + private[chisel3] def initializeInParent(parentCompileOptions: CompileOptions): Unit = () + // Instance name is the same as proto's instance name + override def instanceName = instName() + // Module name is the same as proto's module name + override def desiredName: String = _proto.name + } + + /** Represents a Definition root module, when accessing something from a definition + * + * @note This is necessary to distinguish between the toTarget behavior for a Module returned from a Definition, + * versus a normal Module. A normal Module.toTarget will always return a local target. If calling toTarget + * on a Module returned from a Definition (and thus wrapped in an Instance), we need to return the non-local + * target whose root is the Definition. This DefinitionClone is used to represent the root parent of the + * InstanceClone (which represents the returned module). + */ + private[chisel3] class DefinitionClone[T <: BaseModule] (val _proto: T) extends PseudoModule with IsClone[T] { + override def toString = s"DefinitionClone(${_proto})" + // No addition components are generated + private[chisel3] def generateComponent(): Option[Component] = None + // Necessary for toTarget to work + private[chisel3] def initializeInParent(parentCompileOptions: CompileOptions): Unit = () + // Module name is the same as proto's module name + override def desiredName: String = _proto.name + } + + /** @note If we are cloning a non-module, we need another object which has the proper _parent set! + */ + private[chisel3] final class InstantiableClone[T <: IsInstantiable] (val _proto: T) extends IsClone[T] { + private[chisel3] var _parent: Option[BaseModule] = internal.Builder.currentModule + } + /** Record type returned by CloneModuleAsRecord * * @note These are not true Data (the Record doesn't correspond to anything in the emitted @@ -232,6 +304,9 @@ package internal { // We make this before clonePorts because we want it to come up first in naming in // currentModule val cloneParent = Module(new ModuleClone(proto)) + require(proto.isClosed, "Can't clone a module before module close") + require(cloneParent.getOptionRef.isEmpty, "Can't have ref set already!") + // Fake Module to serve as the _parent of the cloned ports // We don't create this inside the ModuleClone because we need the ref to be set by the // currentModule (and not clonePorts) val clonePorts = new ClonePorts(proto.getModulePorts: _*) @@ -253,10 +328,19 @@ package internal { package experimental { + import chisel3.experimental.hierarchy.IsInstantiable + + object BaseModule { + implicit class BaseModuleExtensions[T <: BaseModule](b: T) { + import chisel3.experimental.hierarchy.{Instance, Definition} + def toInstance: Instance[T] = new Instance(Left(b)) + def toDefinition: Definition[T] = new Definition(Left(b)) + } + } /** Abstract base class for Modules, an instantiable organizational unit for RTL. */ // TODO: seal this? - abstract class BaseModule extends HasId { + abstract class BaseModule extends HasId with IsInstantiable { _parent.foreach(_.addId(this)) // @@ -379,13 +463,24 @@ package experimental { * * @note Should not be called until circuit elaboration is complete */ - final def toNamed: ModuleName = toTarget.toNamed + final def toNamed: ModuleName = ModuleTarget(this.circuitName, this.name).toNamed /** Returns a FIRRTL ModuleTarget that references this object * * @note Should not be called until circuit elaboration is complete */ - final def toTarget: ModuleTarget = ModuleTarget(this.circuitName, this.name) + final def toTarget: IsModule = { + this match { + case m: internal.BaseModule.InstanceClone[_] if m._parent.nonEmpty => m._parent.get.toTarget.instOf(instanceName, name) + case m: internal.BaseModule.InstanceClone[_] => ModuleTarget(this.circuitName, this.name) + case m: internal.BaseModule.ModuleClone[_] if m._madeFromDefinition => m._parent.get.toTarget.instOf(instanceName, name) + case m: internal.BaseModule.ModuleClone[_] => ModuleTarget(this.circuitName, this.name) + // Without this, we get the wrong CircuitName for the Definition + case m: internal.BaseModule.DefinitionClone[_] if m._circuit.nonEmpty => ModuleTarget(this._circuit.get.circuitName, this.name) + case m: internal.BaseModule.DefinitionClone[_] => ModuleTarget(this.circuitName, this.name) + case m => ModuleTarget(this.circuitName, this.name) + } + } /** Returns a FIRRTL ModuleTarget that references this object * @@ -393,7 +488,7 @@ package experimental { */ final def toAbsoluteTarget: IsModule = { _parent match { - case Some(parent) => parent.toAbsoluteTarget.instOf(this.instanceName, toTarget.module) + case Some(parent) => parent.toAbsoluteTarget.instOf(this.instanceName, name) case None => // FIXME Special handling for Views - evidence of "weirdness" of .toAbsoluteTarget // In theory, .toAbsoluteTarget should not be necessary, .toTarget combined with the diff --git a/core/src/main/scala/chisel3/RawModule.scala b/core/src/main/scala/chisel3/RawModule.scala index 74e9db6c..27f16ad4 100644 --- a/core/src/main/scala/chisel3/RawModule.scala +++ b/core/src/main/scala/chisel3/RawModule.scala @@ -7,7 +7,7 @@ import scala.util.Try import scala.language.experimental.macros import chisel3.experimental.{BaseModule, BaseSim} import chisel3.internal._ -import chisel3.internal.BaseModule.ModuleClone +import chisel3.internal.BaseModule.{ModuleClone, InstanceClone} import chisel3.internal.Builder._ import chisel3.internal.firrtl._ import chisel3.internal.sourceinfo.UnlocatableSourceInfo @@ -77,7 +77,8 @@ abstract class RawModule(implicit moduleCompileOptions: CompileOptions) // All suggestions are in, force names to every node. for (id <- getIds) { id match { - case id: ModuleClone => id.setRefAndPortsRef(_namespace) // special handling + case id: ModuleClone[_] => id.setRefAndPortsRef(_namespace) // special handling + case id: InstanceClone[_] => id.setAsInstanceRef() case id: BaseModule => id.forceName(None, default=id.desiredName, _namespace) case id: MemBase[_] => id.forceName(None, default="MEM", _namespace) case id: BaseSim => id.forceName(None, default="SIM", _namespace) @@ -158,6 +159,10 @@ trait RequireSyncReset extends Module { package object internal { + import scala.annotation.implicitNotFound + @implicitNotFound("You are trying to access a macro-only API. Please use the @public annotation instead.") + trait MacroGenerated + /** Marker trait for modules that are not true modules */ private[chisel3] trait PseudoModule extends BaseModule diff --git a/core/src/main/scala/chisel3/experimental/hierarchy/Definition.scala b/core/src/main/scala/chisel3/experimental/hierarchy/Definition.scala new file mode 100644 index 00000000..2e917dfa --- /dev/null +++ b/core/src/main/scala/chisel3/experimental/hierarchy/Definition.scala @@ -0,0 +1,99 @@ +// SPDX-License-Identifier: Apache-2.0 + +package chisel3.experimental.hierarchy + +import scala.language.experimental.macros + +import chisel3._ +import scala.collection.mutable.HashMap +import chisel3.internal.{Builder, DynamicContext} +import chisel3.internal.sourceinfo.{DefinitionTransform, DefinitionWrapTransform, SourceInfo} +import chisel3.experimental.BaseModule +import chisel3.internal.BaseModule.IsClone + +/** User-facing Definition type. + * Represents a definition of an object of type [[A]] which are marked as @instantiable + * Can be created using Definition.apply method. + * + * These definitions are then used to create multiple [[Instance]]s. + * + * @param cloned The internal representation of the instance, which may be either be directly the object, or a clone of an object + */ +case class Definition[+A] private[chisel3] (private[chisel3] cloned: Either[A, IsClone[A]]) extends IsLookupable { + private[chisel3] def proto: A = cloned match { + case Left(value: A) => value + case Right(i: IsClone[A]) => i._proto + } + /** Used by Chisel's internal macros. DO NOT USE in your normal Chisel code!!! + * Instead, mark the field you are accessing with [[@public]] + * + * Given a selector function (that) which selects a member from the original, return the + * corresponding member from the instance. + * + * Our @instantiable and @public macros generate the calls to this apply method + * + * By calling this function, we summon the proper Lookupable typeclass from our implicit scope. + * + * @param that a user-specified lookup function + * @param lookup typeclass which contains the correct lookup function, based on the types of A and B + * @param macroGenerated a value created in the macro, to make it harder for users to use this API + */ + def _lookup[B, C](that: A => B)(implicit lookup: Lookupable[B], macroGenerated: chisel3.internal.MacroGenerated): lookup.C = { + lookup.definitionLookup(that, this) + } + + /** Updated by calls to [[apply]], to avoid recloning returned Data's */ + private [chisel3] val cache = HashMap[Data, Data]() + + + /** @return the context of any Data's return from inside the instance */ + private[chisel3] def getInnerDataContext: Option[BaseModule] = proto match { + case value: BaseModule => + val newChild = Module.do_apply(new internal.BaseModule.DefinitionClone(value))(chisel3.internal.sourceinfo.UnlocatableSourceInfo, chisel3.ExplicitCompileOptions.Strict) + newChild._circuit = value._circuit.orElse(Some(value)) + newChild._parent = None + Some(newChild) + case value: IsInstantiable => None + } + +} + +/** Factory methods for constructing [[Definition]]s */ +object Definition extends SourceInfoDoc { + implicit class DefinitionBaseModuleExtensions[T <: BaseModule](d: Definition[T]) { + /** If this is an instance of a Module, returns the toTarget of this instance + * @return target of this instance + */ + def toTarget = d.proto.toTarget + + /** If this is an instance of a Module, returns the toAbsoluteTarget of this instance + * @return absoluteTarget of this instance + */ + def toAbsoluteTarget = d.proto.toAbsoluteTarget + } + /** A construction method to build a Definition of a Module + * + * @param proto the Module being defined + * + * @return the input module as a Definition + */ + def apply[T <: BaseModule with IsInstantiable](proto: => T): Definition[T] = macro DefinitionTransform.apply[T] + + /** A construction method to build a Definition of a Module + * + * @param bc the Module being defined + * + * @return the input module as a Definition + */ + def do_apply[T <: BaseModule with IsInstantiable](proto: => T) (implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Definition[T] = { + val dynamicContext = new DynamicContext(Nil) + Builder.globalNamespace.copyTo(dynamicContext.globalNamespace) + dynamicContext.inDefinition = true + val (ir, module) = Builder.build(Module(proto), dynamicContext) + Builder.components ++= ir.components + Builder.annotations ++= ir.annotations + module._circuit = Builder.currentModule + dynamicContext.globalNamespace.copyTo(Builder.globalNamespace) + new Definition(Left(module)) + } +} diff --git a/core/src/main/scala/chisel3/experimental/hierarchy/Instance.scala b/core/src/main/scala/chisel3/experimental/hierarchy/Instance.scala new file mode 100644 index 00000000..aec42da3 --- /dev/null +++ b/core/src/main/scala/chisel3/experimental/hierarchy/Instance.scala @@ -0,0 +1,111 @@ +// SPDX-License-Identifier: Apache-2.0 + +package chisel3.experimental.hierarchy + +import scala.collection.mutable.{ArrayBuffer, HashMap} +import scala.language.experimental.macros + +import chisel3._ +import chisel3.internal.BaseModule.{ModuleClone, IsClone, InstantiableClone} +import chisel3.internal.sourceinfo.{InstanceTransform, SourceInfo} +import chisel3.experimental.BaseModule + +/** User-facing Instance type. + * Represents a unique instance of type [[A]] which are marked as @instantiable + * Can be created using Instance.apply method. + * + * @param cloned The internal representation of the instance, which may be either be directly the object, or a clone of an object + */ +case class Instance[+A] private [chisel3] (private[chisel3] cloned: Either[A, IsClone[A]]) { + + /** Returns the original object which is instantiated here. + * If this is an instance of a clone, return that clone's original proto + * + * @return the original object which was instantiated + */ + private[chisel3] def proto: A = cloned match { + case Left(value: A) => value + case Right(i: IsClone[A]) => i._proto + } + + /** @return the context of any Data's return from inside the instance */ + private[chisel3] def getInnerDataContext: Option[BaseModule] = cloned match { + case Left(value: BaseModule) => Some(value) + case Left(value: IsInstantiable) => None + case Right(i: BaseModule) => Some(i) + case Right(i: InstantiableClone[_]) => i._parent + } + + /** @return the context this instance. Note that for non-module clones, getInnerDataContext will be the same as getClonedParent */ + private[chisel3] def getClonedParent: Option[BaseModule] = cloned match { + case Left(value: BaseModule) => value._parent + case Right(i: BaseModule) => i._parent + case Right(i: InstantiableClone[_]) => i._parent + } + + /** Updated by calls to [[apply]], to avoid recloning returned Data's */ + private [chisel3] val cache = HashMap[Data, Data]() + + /** Used by Chisel's internal macros. DO NOT USE in your normal Chisel code!!! + * Instead, mark the field you are accessing with [[@public]] + * + * Given a selector function (that) which selects a member from the original, return the + * corresponding member from the instance. + * + * Our @instantiable and @public macros generate the calls to this apply method + * + * By calling this function, we summon the proper Lookupable typeclass from our implicit scope. + * + * @param that a user-specified lookup function + * @param lookup typeclass which contains the correct lookup function, based on the types of A and B + * @param macroGenerated a value created in the macro, to make it harder for users to use this API + */ + def _lookup[B, C](that: A => B)(implicit lookup: Lookupable[B], macroGenerated: chisel3.internal.MacroGenerated): lookup.C = { + lookup.instanceLookup(that, this) + } + + /** Returns the definition of this Instance */ + def toDefinition: Definition[A] = new Definition(Left(proto)) + +} + +/** Factory methods for constructing [[Instance]]s */ +object Instance extends SourceInfoDoc { + implicit class InstanceBaseModuleExtensions[T <: BaseModule](i: Instance[T]) { + /** If this is an instance of a Module, returns the toTarget of this instance + * @return target of this instance + */ + def toTarget = i.cloned match { + case Left(x: BaseModule) => x.toTarget + case Right(x: IsClone[_] with BaseModule) => x.toTarget + } + + /** If this is an instance of a Module, returns the toAbsoluteTarget of this instance + * @return absoluteTarget of this instance + */ + def toAbsoluteTarget = i.cloned match { + case Left(x) => x.toAbsoluteTarget + case Right(x: IsClone[_] with BaseModule) => x.toAbsoluteTarget + } + + } + /** A constructs an [[Instance]] from a [[Definition]] + * + * @param definition the Module being created + * @return an instance of the module definition + */ + def apply[T <: BaseModule with IsInstantiable](definition: Definition[T]): Instance[T] = macro InstanceTransform.apply[T] + + /** A constructs an [[Instance]] from a [[Definition]] + * + * @param definition the Module being created + * @return an instance of the module definition + */ + def do_apply[T <: BaseModule with IsInstantiable](definition: Definition[T])(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Instance[T] = { + val ports = experimental.CloneModuleAsRecord(definition.proto) + val clone = ports._parent.get.asInstanceOf[ModuleClone[T]] + clone._madeFromDefinition = true + new Instance(Right(clone)) + } + +} diff --git a/core/src/main/scala/chisel3/experimental/hierarchy/IsInstantiable.scala b/core/src/main/scala/chisel3/experimental/hierarchy/IsInstantiable.scala new file mode 100644 index 00000000..26ba0286 --- /dev/null +++ b/core/src/main/scala/chisel3/experimental/hierarchy/IsInstantiable.scala @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: Apache-2.0 + +package chisel3.experimental.hierarchy + +/** While this is public, it is not recommended for users to extend directly. + * Instead, use the [[@instantiable]] annotation on your trait or class. + * + * This trait indicates whether a class can be returned from an Instance. + * + */ +trait IsInstantiable + +object IsInstantiable { + implicit class IsInstantiableExtensions[T <: IsInstantiable](i: T) { + def toInstance: Instance[T] = new Instance(Left(i)) + } +} diff --git a/core/src/main/scala/chisel3/experimental/hierarchy/IsLookupable.scala b/core/src/main/scala/chisel3/experimental/hierarchy/IsLookupable.scala new file mode 100644 index 00000000..37d29a43 --- /dev/null +++ b/core/src/main/scala/chisel3/experimental/hierarchy/IsLookupable.scala @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: Apache-2.0 + +package chisel3.experimental.hierarchy + +/** A User-extendable trait to mark metadata-containers, e.g. parameter case classes, as valid to return unchanged + * from an instance. + * + * This should only be true of the metadata returned is identical for ALL instances! + * + * @example For instances of the same proto, metadata or other construction parameters + * may be useful to access outside of the instance construction. For parameters that are + * the same for all instances, we should mark it as IsLookupable + * {{{ + * case class Params(debugMessage: String) extends IsLookupable + * class MyModule(p: Params) extends MultiIOModule { + * printf(p.debugMessage) + * } + * val myParams = Params("Hello World") + * val definition = Definition(new MyModule(myParams)) + * val i0 = Instance(definition) + * val i1 = Instance(definition) + * require(i0.p == i1.p) // p is only accessable because it extends IsLookupable + * }}} + */ +trait IsLookupable diff --git a/core/src/main/scala/chisel3/experimental/hierarchy/Lookupable.scala b/core/src/main/scala/chisel3/experimental/hierarchy/Lookupable.scala new file mode 100644 index 00000000..b9617723 --- /dev/null +++ b/core/src/main/scala/chisel3/experimental/hierarchy/Lookupable.scala @@ -0,0 +1,368 @@ +// SPDX-License-Identifier: Apache-2.0 + +package chisel3.experimental.hierarchy + +import chisel3.experimental.BaseModule +import chisel3.internal.sourceinfo.SourceInfo +import chisel3.internal.BaseModule.{InstanceClone, InstantiableClone, IsClone, ModuleClone} + +import scala.annotation.implicitNotFound +import scala.collection.mutable.HashMap +import chisel3._ +import chisel3.experimental.dataview.{isView, reify, reifySingleData} +import chisel3.internal.firrtl.{Arg, ILit, Index, Slot, ULit} +import chisel3.internal.{AggregateViewBinding, Builder, ChildBinding, ViewBinding, ViewParent, throwException} + +/** Represents lookup typeclass to determine how a value accessed from an original IsInstantiable + * should be tweaked to return the Instance's version + * Sealed. + */ +@implicitNotFound("@public is only legal within a class marked @instantiable and only on vals of type" + + " Data, BaseModule, IsInstantiable, IsLookupable, or Instance[_], or in an Iterable or Option") +sealed trait Lookupable[-B] { + type C // Return type of the lookup + /** Function called to modify the returned value of type B from A, into C + * + * @param that function that selects B from A + * @param instance Instance of A, used to determine C's context + * @return + */ + def instanceLookup[A](that: A => B, instance: Instance[A]): C + + /** Function called to modify the returned value of type B from A, into C + * + * @param that function that selects B from A + * @param definition Definition of A, used to determine C's context + * @return + */ + def definitionLookup[A](that: A => B, definition: Definition[A]): C +} + +private[chisel3] object Lookupable { + + /** Clones a data and sets its internal references to its parent module to be in a new context. + * + * @param data data to be cloned + * @param context new context + * @return + */ + private[chisel3] def cloneDataToContext[T <: Data](data: T, context: BaseModule) + (implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): T = { + internal.requireIsHardware(data, "cross module reference type") + data._parent match { + case None => data + case Some(parent) => + val newParent = cloneModuleToContext(Left(parent), context) + newParent match { + case Left(p) if p == parent => data + case Right(m: BaseModule) => + val newChild = data.cloneTypeFull + newChild.setRef(data.getRef, true) + newChild.bind(internal.CrossModuleBinding) + newChild.setAllParents(Some(m)) + newChild + } + } + } + // The business logic of lookupData + // Also called by cloneViewToContext which potentially needs to lookup stuff from ioMap or the cache + private[chisel3] def doLookupData[A, B <: Data](data: B, cache: HashMap[Data, Data], ioMap: Option[Map[Data, Data]], context: Option[BaseModule]) + (implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): B = { + def impl[C <: Data](d: C): C = d match { + case x: Data if ioMap.nonEmpty && ioMap.get.contains(x) => ioMap.get(x).asInstanceOf[C] + case x: Data if cache.contains(x) => cache(x).asInstanceOf[C] + case _ => + assert(context.nonEmpty) // TODO is this even possible? Better error message here + val ret = cloneDataToContext(d, context.get) + cache(d) = ret + ret + } + data.binding match { + case Some(_: ChildBinding) => mapRootAndExtractSubField(data, impl) + case _ => impl(data) + } + } + + // Helper for co-iterating on Elements of aggregates, they must be the same type but that is unchecked + private def coiterate(a: Data, b: Data): Iterable[(Element, Element)] = { + val as = getRecursiveFields.lazily(a, "_") + val bs = getRecursiveFields.lazily(b, "_") + as.zip(bs).collect { case ((ae: Element, _), (be: Element, _)) => (ae, be) } + } + + /** Given a Data, find the root of its binding, apply a function to the root to get a "new root", + * and find the equivalent child Data in the "new root" + * + * @example {{{ + * Given `arg = a.b[2].c` and some `f`: + * 1. a = root(arg) = root(a.b[2].c) + * 2. newRoot = f(root(arg)) = f(a) + * 3. return newRoot.b[2].c + * }}} + * + * Invariants that elt is a Child of something of the type of data is dynamically checked as we traverse + */ + private def mapRootAndExtractSubField[A <: Data](arg: A, f: Data => Data): A = { + def err(msg: String) = throwException(s"Internal Error! $msg") + def unrollCoordinates(res: List[Arg], d: Data): (List[Arg], Data) = d.binding.get match { + case ChildBinding(parent) => d.getRef match { + case arg @ (_: Slot | _: Index) => unrollCoordinates(arg :: res, parent) + case other => err(s"Unroll coordinates failed for '$arg'! Unexpected arg '$other'") + } + case _ => (res, d) + } + def applyCoordinates(fullCoor: List[Arg], start: Data): Data = { + def rec(coor: List[Arg], d: Data): Data = { + if (coor.isEmpty) d + else { + val next = (coor.head, d) match { + case (Slot(_, name), rec: Record) => rec.elements(name) + case (Index(_, ILit(n)), vec: Vec[_]) => vec.apply(n.toInt) + case (arg, _) => err(s"Unexpected Arg '$arg' applied to '$d'! Root was '$start'.") + } + applyCoordinates(coor.tail, next) + } + } + rec(fullCoor, start) + } + val (coor, root) = unrollCoordinates(Nil, arg) + val newRoot = f(root) + val result = applyCoordinates(coor, newRoot) + try { + result.asInstanceOf[A] + } catch { + case _: ClassCastException => err(s"Applying '$coor' to '$newRoot' somehow resulted in '$result'") + } + } + + // TODO this logic is complicated, can any of it be unified with viewAs? + // If `.viewAs` would capture its arguments, we could potentially use it + // TODO Describe what this is doing at a high level + private[chisel3] def cloneViewToContext[A, B <: Data](data: B, cache: HashMap[Data, Data], ioMap: Option[Map[Data, Data]], context: Option[BaseModule]) + (implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): B = { + // alias to shorten lookups + def lookupData[C <: Data](d: C) = doLookupData(d, cache, ioMap, context) + + val result = data.cloneTypeFull + + // We have to lookup the target(s) of the view since they may need to be cloned into the current context + val newBinding = data.topBinding match { + case ViewBinding(target) => ViewBinding(lookupData(reify(target))) + case avb @ AggregateViewBinding(map, targetOpt) => data match { + case _: Element => ViewBinding(lookupData(reify(map(data)))) + case _: Aggregate => + // Provide a 1:1 mapping if possible + val singleTargetOpt = targetOpt.filter(_ => avb == data.binding.get).flatMap(reifySingleData) + singleTargetOpt match { + case Some(singleTarget) => // It is 1:1! + // This is a little tricky because the values in newMap need to point to Elements of newTarget + val newTarget = lookupData(singleTarget) + val newMap = coiterate(result, data).map { case (res, from) => + (res: Data) -> mapRootAndExtractSubField(map(from), _ => newTarget) + }.toMap + AggregateViewBinding(newMap, Some(newTarget)) + + case None => // No 1:1 mapping so we have to do a flat binding + // Just remap each Element of this aggregate + val newMap = coiterate(result, data).map { + // Upcast res to Data since Maps are invariant in the Key type parameter + case (res, from) => (res: Data) -> lookupData(reify(map(from))) + }.toMap + AggregateViewBinding(newMap, None) + } + } + } + + // TODO Unify the following with `.viewAs` + // We must also mark non-1:1 and child Aggregates in the view for renaming + newBinding match { + case _: ViewBinding => // Do nothing + case AggregateViewBinding(_, target) => + if (target.isEmpty) { + Builder.unnamedViews += result + } + // Binding does not capture 1:1 for child aggregates views + getRecursiveFields.lazily(result, "_").foreach { + case (agg: Aggregate, _) if agg != result => + Builder.unnamedViews += agg + case _ => // Do nothing + } + } + + result.bind(newBinding) + result.setAllParents(Some(ViewParent)) + result.forceName(None, "view", Builder.viewNamespace) + result + } + /** Given a module (either original or a clone), clone it to a new context + * + * This function effectively recurses up the parents of module to find whether: + * (1) A parent is already in the context; then we do nothing and return module + * (2) A parent is in a different clone of the context; then we clone all the parents up + * to that parent and set their parents to be in this cloned context + * (3) A parent has no root; in that case, we do nothing and return the module. + * + * @param module original or clone to be cloned into a new context + * @param context new context + * @return original or clone in the new context + */ + private[chisel3] def cloneModuleToContext[T <: BaseModule](module: Either[T, IsClone[T]], context: BaseModule) + (implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Either[T, IsClone[T]] = { + // Recursive call + def rec[A <: BaseModule](m: A): Either[A, IsClone[A]] = { + def clone(x: A, p: Option[BaseModule], name: () => String): Either[A, IsClone[A]] = { + val newChild = Module.do_apply(new internal.BaseModule.InstanceClone(x, name)) + newChild._parent = p + Right(newChild) + } + (m, context) match { + case (c, ctx) if ctx == c => Left(c) + case (c, ctx: IsClone[_]) if ctx.isACloneOf(c) => Right(ctx.asInstanceOf[IsClone[A]]) + case (c, ctx) if c._parent.isEmpty => Left(c) + case (_, _) => + cloneModuleToContext(Left(m._parent.get), context) match { + case Left(p) => Left(m) + case Right(p: BaseModule) => + clone(m, Some(p), () => m.instanceName) + } + } + } + module match { + case Left(m) => rec(m) + case Right(m: ModuleClone[_]) => + rec(m) match { + case Left(mx) => Right(mx) + case Right(i: InstanceClone[_]) => + val newChild = Module.do_apply(new InstanceClone(m._proto, () => m.instanceName)) + newChild._parent = i._parent + Right(newChild) + } + case Right(m: InstanceClone[_]) => + rec(m) match { + case Left(mx) => Right(mx) + case Right(i: InstanceClone[_]) => + val newChild = Module.do_apply(new InstanceClone(m._proto, () => m.instanceName)) + newChild._parent = i._parent + Right(newChild) + } + } + } + + class SimpleLookupable[X] extends Lookupable[X] { + type B = X + type C = X + def definitionLookup[A](that: A => B, definition: Definition[A]): C = that(definition.proto) + def instanceLookup[A](that: A => B, instance: Instance[A]): C = that(instance.proto) + } + + implicit def lookupInstance[B <: BaseModule](implicit sourceInfo: SourceInfo, compileOptions: CompileOptions) = new Lookupable[Instance[B]] { + type C = Instance[B] + def definitionLookup[A](that: A => Instance[B], definition: Definition[A]): C = { + val ret = that(definition.proto) + new Instance(cloneModuleToContext(ret.cloned, definition.getInnerDataContext.get)) + } + def instanceLookup[A](that: A => Instance[B], instance: Instance[A]): C = { + val ret = that(instance.proto) + instance.cloned match { + // If instance is just a normal module, no changing of context is necessary + case Left(_) => new Instance(ret.cloned) + case Right(_) => new Instance(cloneModuleToContext(ret.cloned, instance.getInnerDataContext.get)) + } + } + } + + implicit def lookupModule[B <: BaseModule](implicit sourceInfo: SourceInfo, compileOptions: CompileOptions) = new Lookupable[B] { + type C = Instance[B] + def definitionLookup[A](that: A => B, definition: Definition[A]): C = { + val ret = that(definition.proto) + new Instance(cloneModuleToContext(Left(ret), definition.getInnerDataContext.get)) + } + def instanceLookup[A](that: A => B, instance: Instance[A]): C = { + val ret = that(instance.proto) + instance.cloned match { + // If instance is just a normal module, no changing of context is necessary + case Left(_) => new Instance(Left(ret)) + case Right(_) => new Instance(cloneModuleToContext(Left(ret), instance.getInnerDataContext.get)) + } + } + } + + implicit def lookupData[B <: Data](implicit sourceInfo: SourceInfo, compileOptions: CompileOptions) = new Lookupable[B] { + type C = B + def definitionLookup[A](that: A => B, definition: Definition[A]): C = { + val ret = that(definition.proto) + if (isView(ret)) { + ??? // TODO!!!!!! cloneViewToContext(ret, instance, ioMap, instance.getInnerDataContext) + } else { + doLookupData(ret, definition.cache, None, definition.getInnerDataContext) + } + } + def instanceLookup[A](that: A => B, instance: Instance[A]): C = { + val ret = that(instance.proto) + val ioMap: Option[Map[Data, Data]] = instance.cloned match { + case Right(x: ModuleClone[_]) => Some(x.ioMap) + case Left(x: BaseModule) => Some(x.getChiselPorts.map { case (_, data) => data -> data }.toMap) + case _ => None + } + if (isView(ret)) { + cloneViewToContext(ret, instance.cache, ioMap, instance.getInnerDataContext) + } else { + doLookupData(ret, instance.cache, ioMap, instance.getInnerDataContext) + } + + } + } + + import scala.language.higherKinds // Required to avoid warning for lookupIterable type parameter + implicit def lookupIterable[B, F[_] <: Iterable[_]](implicit sourceInfo: SourceInfo, compileOptions: CompileOptions, lookupable: Lookupable[B]) = new Lookupable[F[B]] { + type C = F[lookupable.C] + def definitionLookup[A](that: A => F[B], definition: Definition[A]): C = { + val ret = that(definition.proto).asInstanceOf[Iterable[B]] + ret.map{ x: B => lookupable.definitionLookup[A](_ => x, definition) }.asInstanceOf[C] + } + def instanceLookup[A](that: A => F[B], instance: Instance[A]): C = { + import instance._ + val ret = that(proto).asInstanceOf[Iterable[B]] + ret.map{ x: B => lookupable.instanceLookup[A](_ => x, instance) }.asInstanceOf[C] + } + } + implicit def lookupOption[B](implicit sourceInfo: SourceInfo, compileOptions: CompileOptions, lookupable: Lookupable[B]) = new Lookupable[Option[B]] { + type C = Option[lookupable.C] + def definitionLookup[A](that: A => Option[B], definition: Definition[A]): C = { + val ret = that(definition.proto) + ret.map{ x: B => lookupable.definitionLookup[A](_ => x, definition) } + } + def instanceLookup[A](that: A => Option[B], instance: Instance[A]): C = { + import instance._ + val ret = that(proto) + ret.map{ x: B => lookupable.instanceLookup[A](_ => x, instance) } + } + } + implicit def lookupIsInstantiable[B <: IsInstantiable](implicit sourceInfo: SourceInfo, compileOptions: CompileOptions) = new Lookupable[B] { + type C = Instance[B] + def definitionLookup[A](that: A => B, definition: Definition[A]): C = { + val ret = that(definition.proto) + val cloned = new InstantiableClone(ret) + cloned._parent = definition.getInnerDataContext + new Instance(Right(cloned)) + } + def instanceLookup[A](that: A => B, instance: Instance[A]): C = { + val ret = that(instance.proto) + val cloned = new InstantiableClone(ret) + cloned._parent = instance.getInnerDataContext + new Instance(Right(cloned)) + } + } + + implicit def lookupIsLookupable[B <: IsLookupable](implicit sourceInfo: SourceInfo, compileOptions: CompileOptions) = new SimpleLookupable[B]() + + implicit val lookupInt = new SimpleLookupable[Int]() + implicit val lookupByte = new SimpleLookupable[Byte]() + implicit val lookupShort = new SimpleLookupable[Short]() + implicit val lookupLong = new SimpleLookupable[Long]() + implicit val lookupFloat = new SimpleLookupable[Float]() + implicit val lookupChar = new SimpleLookupable[Char]() + implicit val lookupString = new SimpleLookupable[String]() + implicit val lookupBoolean = new SimpleLookupable[Boolean]() + implicit val lookupBigInt = new SimpleLookupable[BigInt]() +} diff --git a/core/src/main/scala/chisel3/experimental/hierarchy/package.scala b/core/src/main/scala/chisel3/experimental/hierarchy/package.scala new file mode 100644 index 00000000..c309ab52 --- /dev/null +++ b/core/src/main/scala/chisel3/experimental/hierarchy/package.scala @@ -0,0 +1,48 @@ +package chisel3.experimental + +package object hierarchy { + + /** Classes or traits which will be used with the [[Definition]] + [[Instance]] api should be marked + * with the [[@instantiable]] annotation at the class/trait definition. + * + * @example {{{ + * @instantiable + * class MyModule extends Module { + * ... + * } + * + * val d = Definition(new MyModule) + * val i0 = Instance(d) + * val i1 = Instance(d) + * }}} + */ + class instantiable extends chisel3.internal.instantiable + + /** Classes marked with [[@instantiable]] can have their vals marked with the [[@public]] annotation to + * enable accessing these values from a [[Definition]] or [[Instance]] of the class. + * + * Only vals of the the following types can be marked [[@public]]: + * 1. IsInstantiable + * 2. IsLookupable + * 3. Data + * 4. BaseModule + * 5. Iterable/Option containing a type that meets these requirements + * 6. Basic type like String, Int, BigInt etc. + * + * @example {{{ + * @instantiable + * class MyModule extends Module { + * @public val in = IO(Input(UInt(3.W))) + * @public val out = IO(Output(UInt(3.W))) + * .. + * } + * + * val d = Definition(new MyModule) + * val i0 = Instance(d) + * val i1 = Instance(d) + * + * i1.in := i0.out + * }}} + */ + class public extends chisel3.internal.public +} diff --git a/core/src/main/scala/chisel3/internal/Binding.scala b/core/src/main/scala/chisel3/internal/Binding.scala index 6f4ab4b0..a0dcc20c 100644 --- a/core/src/main/scala/chisel3/internal/Binding.scala +++ b/core/src/main/scala/chisel3/internal/Binding.scala @@ -129,6 +129,11 @@ private[chisel3] case class ViewBinding(target: Element) extends UnconstrainedBi private[chisel3] case class AggregateViewBinding(childMap: Map[Data, Element], target: Option[Data]) extends UnconstrainedBinding +/** Binding for Data's returned from accessing an Instance/Definition members, if not readable/writable port */ +private[chisel3] case object CrossModuleBinding extends TopBinding { + def location = None +} + sealed trait LitBinding extends UnconstrainedBinding with ReadOnlyBinding // Literal binding attached to a element that is not part of a Bundle. case class ElementLitBinding(litArg: LitArg) extends LitBinding diff --git a/core/src/main/scala/chisel3/internal/Builder.scala b/core/src/main/scala/chisel3/internal/Builder.scala index f7306d5d..1d15247d 100644 --- a/core/src/main/scala/chisel3/internal/Builder.scala +++ b/core/src/main/scala/chisel3/internal/Builder.scala @@ -6,6 +6,7 @@ import scala.util.DynamicVariable import scala.collection.mutable.ArrayBuffer import chisel3._ import chisel3.experimental._ +import chisel3.experimental.hierarchy.Instance import chisel3.internal.firrtl._ import chisel3.internal.naming._ import _root_.firrtl.annotations.{CircuitName, ComponentName, IsMember, ModuleName, Named, ReferenceTarget} @@ -19,6 +20,7 @@ import scala.collection.mutable private[chisel3] class Namespace(keywords: Set[String]) { private val names = collection.mutable.HashMap[String, Long]() + def copyTo(other: Namespace): Unit = names.foreach { case (s: String, l: Long) => other.names(s) = l } for (keyword <- keywords) names(keyword) = 1 @@ -87,6 +89,9 @@ private[chisel3] trait HasId extends InstanceId { private[chisel3] def _onModuleClose: Unit = {} private[chisel3] var _parent: Option[BaseModule] = Builder.currentModule + // Set if the returned top-level module of a nested call to the Chisel Builder, see Definition.apply + private[chisel3] var _circuit: Option[BaseModule] = None + private[chisel3] val _id: Long = Builder.idGen.next // TODO: remove this, but its removal seems to cause a nasty Scala compiler crash. @@ -216,7 +221,7 @@ private[chisel3] trait HasId extends InstanceId { private[chisel3] def getRef: Arg = _ref.get private[chisel3] def getOptionRef: Option[Arg] = _ref - private def localName(c: Component): String = _ref match { + private def refName(c: Component): String = _ref match { case Some(arg) => arg fullName c case None => computeName(None, None).get } @@ -232,11 +237,13 @@ private[chisel3] trait HasId extends InstanceId { // Implementation of public methods. def instanceName: String = _parent match { - case Some(ViewParent) => reifyTarget.map(_.instanceName).getOrElse(this.localName(ViewParent.fakeComponent)) - case Some(p) => p._component match { - case Some(c) => localName(c) - case None => throwException("signalName/pathName should be called after circuit elaboration") - } + case Some(ViewParent) => reifyTarget.map(_.instanceName).getOrElse(this.refName(ViewParent.fakeComponent)) + case Some(p) => + (p._component, this) match { + case (Some(c), _) => refName(c) + case (None, d: Data) if d.topBindingOpt == Some(CrossModuleBinding) => _ref.get.localName + case (None, _) => throwException(s"signalName/pathName should be called after circuit elaboration: $this, ${_parent}") + } case None => throwException("this cannot happen") } def pathName: String = _parent match { @@ -256,7 +263,10 @@ private[chisel3] trait HasId extends InstanceId { } // TODO Should this be public? protected def circuitName: String = _parent match { - case None => instanceName + case None => _circuit match { + case None => instanceName + case Some(o) => o.circuitName + } case Some(ViewParent) => reifyParent.circuitName case Some(p) => p.circuitName } @@ -296,8 +306,12 @@ private[chisel3] trait NamedComponent extends HasId { val name = this.instanceName if (!validComponentName(name)) throwException(s"Illegal component name: $name (note: literals are illegal)") import _root_.firrtl.annotations.{Target, TargetToken} + val root = _parent.map { + case ViewParent => reifyParent + case other => other + }.get.toTarget // All NamedComponents will have a parent, only the top module can have None here Target.toTargetTokens(name).toList match { - case TargetToken.Ref(r) :: components => ReferenceTarget(this.circuitName, this.parentModName, Nil, r, components) + case TargetToken.Ref(r) :: components => root.ref(r).copy(component = components) case other => throw _root_.firrtl.annotations.Target.NamedException(s"Cannot convert $name into [[ReferenceTarget]]: $other") } @@ -354,6 +368,8 @@ private[chisel3] class DynamicContext(val annotationSeq: AnnotationSeq) { var currentReset: Option[Reset] = None val errors = new ErrorLog val namingStack = new NamingStack + // Used to indicate if this is the top-level module of full elaboration, or from a Definition + var inDefinition: Boolean = false } private[chisel3] object Builder extends LazyLogging { @@ -368,6 +384,11 @@ private[chisel3] object Builder extends LazyLogging { dynamicContextVar.value.get } + // Returns the current dynamic context + def captureContext(): DynamicContext = dynamicContext + // Sets the current dynamic contents + def restoreContext(dc: DynamicContext) = dynamicContextVar.value = Some(dc) + // Ensure we have a thread-specific ChiselContext private val chiselContext = new ThreadLocal[ChiselContext]{ override def initialValue: ChiselContext = { @@ -563,6 +584,12 @@ private[chisel3] object Builder extends LazyLogging { dynamicContext.currentReset = newReset } + def inDefinition: Boolean = { + dynamicContextVar.value + .map(_.inDefinition) + .getOrElse(false) + } + // This should only be used for testing, must be true outside of Builder context def allowReflectiveAutoCloneType: Boolean = { dynamicContextVar.value @@ -632,6 +659,10 @@ private[chisel3] object Builder extends LazyLogging { * (Note: Map is Iterable[Tuple2[_,_]] and thus excluded) */ def nameRecursively(prefix: String, nameMe: Any, namer: (HasId, String) => Unit): Unit = nameMe match { + case (id: Instance[_]) => id.cloned match { + case Right(m: internal.BaseModule.ModuleClone[_]) => namer(m.getPorts, prefix) + case _ => + } case (id: HasId) => namer(id, prefix) case Some(elt) => nameRecursively(prefix, elt, namer) case (iter: Iterable[_]) if iter.hasDefiniteSize => @@ -696,7 +727,7 @@ private[chisel3] object Builder extends LazyLogging { renames } - private [chisel3] def build[T <: RawModule](f: => T, dynamicContext: DynamicContext): (Circuit, T) = { + private [chisel3] def build[T <: BaseModule](f: => T, dynamicContext: DynamicContext): (Circuit, T) = { dynamicContextVar.withValue(Some(dynamicContext)) { ViewParent // Must initialize the singleton in a Builder context or weird things can happen // in tiny designs/testcases that never access anything in chisel3.internal diff --git a/core/src/main/scala/chisel3/internal/firrtl/IR.scala b/core/src/main/scala/chisel3/internal/firrtl/IR.scala index f8a3cf7f..0b568548 100644 --- a/core/src/main/scala/chisel3/internal/firrtl/IR.scala +++ b/core/src/main/scala/chisel3/internal/firrtl/IR.scala @@ -65,13 +65,19 @@ object PrimOp { } abstract class Arg { - def fullName(ctx: Component): String = name + def localName: String = name + def contextualName(ctx: Component): String = name + def fullName(ctx: Component): String = contextualName(ctx) def name: String } case class Node(id: HasId) extends Arg { - override def fullName(ctx: Component): String = id.getOptionRef match { - case Some(arg) => arg.fullName(ctx) + override def contextualName(ctx: Component): String = id.getOptionRef match { + case Some(arg) => arg.contextualName(ctx) + case None => id.instanceName + } + override def localName: String = id.getOptionRef match { + case Some(arg) => arg.localName case None => id.instanceName } def name: String = id.getOptionRef match { @@ -83,7 +89,7 @@ case class Node(id: HasId) extends Arg { abstract class LitArg(val num: BigInt, widthArg: Width) extends Arg { private[chisel3] def forcedWidth = widthArg.known private[chisel3] def width: Width = if (forcedWidth) widthArg else Width(minWidth) - override def fullName(ctx: Component): String = name + override def contextualName(ctx: Component): String = name // Ensure the node representing this LitArg has a ref to it and a literal binding. def bindLitArg[T <: Element](elem: T): T = { elem.bind(ElementLitBinding(this)) @@ -167,7 +173,7 @@ case class Ref(name: String) extends Arg * @param name the name of the port */ case class ModuleIO(mod: BaseModule, name: String) extends Arg { - override def fullName(ctx: Component): String = + override def contextualName(ctx: Component): String = if (mod eq ctx.id) name else s"${mod.getRef.name}.$name" } /** Ports of cloned modules (CloneModuleAsRecord) @@ -175,19 +181,25 @@ case class ModuleIO(mod: BaseModule, name: String) extends Arg { * @param name the name of the module instance */ case class ModuleCloneIO(mod: BaseModule, name: String) extends Arg { - override def fullName(ctx: Component): String = + override def localName = "" + override def contextualName(ctx: Component): String = // NOTE: mod eq ctx.id only occurs in Target and Named-related APIs - if (mod eq ctx.id) "" else name + if (mod eq ctx.id) localName else name } case class Slot(imm: Node, name: String) extends Arg { - override def fullName(ctx: Component): String = { - val immName = imm.fullName(ctx) + override def contextualName(ctx: Component): String = { + val immName = imm.contextualName(ctx) + if (immName.isEmpty) name else s"$immName.$name" + } + override def localName: String = { + val immName = imm.localName if (immName.isEmpty) name else s"$immName.$name" } } case class Index(imm: Arg, value: Arg) extends Arg { def name: String = s"[$value]" - override def fullName(ctx: Component): String = s"${imm.fullName(ctx)}[${value.fullName(ctx)}]" + override def contextualName(ctx: Component): String = s"${imm.contextualName(ctx)}[${value.contextualName(ctx)}]" + override def localName: String = s"${imm.localName}[${value.localName}]" } object Width { @@ -792,4 +804,5 @@ case class DefBlackBox(id: BaseBlackBox, name: String, ports: Seq[Port], topDir: case class Circuit(name: String, components: Seq[Component], annotations: Seq[ChiselAnnotation], renames: RenameMap) { def firrtlAnnotations: Iterable[Annotation] = annotations.flatMap(_.toFirrtl.update(renames)) + } -- cgit v1.2.3 From 2b51053fe7744d6860416c7de8bcb99d4aa9e532 Mon Sep 17 00:00:00 2001 From: Jack Koenig Date: Wed, 8 Sep 2021 14:31:10 -0700 Subject: Restore return type of BaseModule.toTarget to ModuleTarget (#2117) Definition/Instance introduced the need for representing the targets of instances as InstanceTargets. This original implementation changed the return type of BaseModule.toTarget to express this need. This is a backwards incompatible change that is actually unnecessary because it is impossible for users to get references to the internal InstanceClone objects, instead only accessing such modules via Instance[_] wrappers and cloned Data. We restored the old API by adding a new internal method "getTarget" which will give the correct targets for InstanceClones while maintaining the API of BaseModule.toTarget.--- core/src/main/scala/chisel3/Module.scala | 36 ++++++++++++++-------- .../experimental/hierarchy/Definition.scala | 7 +++-- .../chisel3/experimental/hierarchy/Instance.scala | 12 ++++---- core/src/main/scala/chisel3/internal/Builder.scala | 2 +- 4 files changed, 35 insertions(+), 22 deletions(-) (limited to 'core/src') diff --git a/core/src/main/scala/chisel3/Module.scala b/core/src/main/scala/chisel3/Module.scala index d0171693..3ae48821 100644 --- a/core/src/main/scala/chisel3/Module.scala +++ b/core/src/main/scala/chisel3/Module.scala @@ -469,17 +469,29 @@ package experimental { * * @note Should not be called until circuit elaboration is complete */ - final def toTarget: IsModule = { - this match { - case m: internal.BaseModule.InstanceClone[_] if m._parent.nonEmpty => m._parent.get.toTarget.instOf(instanceName, name) - case m: internal.BaseModule.InstanceClone[_] => ModuleTarget(this.circuitName, this.name) - case m: internal.BaseModule.ModuleClone[_] if m._madeFromDefinition => m._parent.get.toTarget.instOf(instanceName, name) - case m: internal.BaseModule.ModuleClone[_] => ModuleTarget(this.circuitName, this.name) - // Without this, we get the wrong CircuitName for the Definition - case m: internal.BaseModule.DefinitionClone[_] if m._circuit.nonEmpty => ModuleTarget(this._circuit.get.circuitName, this.name) - case m: internal.BaseModule.DefinitionClone[_] => ModuleTarget(this.circuitName, this.name) - case m => ModuleTarget(this.circuitName, this.name) - } + final def toTarget: ModuleTarget = this match { + case m: internal.BaseModule.InstanceClone[_] => throwException(s"Internal Error! It's not legal to call .toTarget on an InstanceClone. $m") + case m: internal.BaseModule.DefinitionClone[_] => throwException(s"Internal Error! It's not legal to call .toTarget on an DefinitionClone. $m") + case _ => ModuleTarget(this.circuitName, this.name) + } + + /** Returns the real target of a Module which may be an [[InstanceTarget]] + * + * BaseModule.toTarget returns a ModuleTarget because the classic Module(new MyModule) API elaborates + * Modules in a way that there is a 1:1 relationship between instances and elaborated definitions + * + * Instance/Definition introduced special internal modules [[InstanceClone]] and [[ModuleClone]] that + * do not have this 1:1 relationship so need the ability to return [[InstanceTarget]]s. + * Because users can never actually get references to these underlying objects, we can maintain + * BaseModule.toTarget's API returning [[ModuleTarget]] while providing an internal API for getting + * the correct [[InstanceTarget]]s whenever using the Definition/Instance API. + */ + private[chisel3] def getTarget: IsModule = this match { + case m: internal.BaseModule.InstanceClone[_] if m._parent.nonEmpty => m._parent.get.getTarget.instOf(instanceName, name) + case m: internal.BaseModule.ModuleClone[_] if m._madeFromDefinition => m._parent.get.getTarget.instOf(instanceName, name) + // Without this, we get the wrong CircuitName for the Definition + case m: internal.BaseModule.DefinitionClone[_] if m._circuit.nonEmpty => ModuleTarget(this._circuit.get.circuitName, this.name) + case _ => this.toTarget } /** Returns a FIRRTL ModuleTarget that references this object @@ -496,7 +508,7 @@ package experimental { // is always unambigous. However, legacy workarounds for Chisel's lack of an instance API // have lead some to use .toAbsoluteTarget as a workaround. A proper instance API will make // it possible to deprecate and remove .toAbsoluteTarget - if (this == ViewParent) ViewParent.absoluteTarget else toTarget + if (this == ViewParent) ViewParent.absoluteTarget else getTarget } } diff --git a/core/src/main/scala/chisel3/experimental/hierarchy/Definition.scala b/core/src/main/scala/chisel3/experimental/hierarchy/Definition.scala index 2e917dfa..0cc3d131 100644 --- a/core/src/main/scala/chisel3/experimental/hierarchy/Definition.scala +++ b/core/src/main/scala/chisel3/experimental/hierarchy/Definition.scala @@ -3,13 +3,14 @@ package chisel3.experimental.hierarchy import scala.language.experimental.macros - import chisel3._ + import scala.collection.mutable.HashMap import chisel3.internal.{Builder, DynamicContext} import chisel3.internal.sourceinfo.{DefinitionTransform, DefinitionWrapTransform, SourceInfo} import chisel3.experimental.BaseModule import chisel3.internal.BaseModule.IsClone +import firrtl.annotations.{IsModule, ModuleTarget} /** User-facing Definition type. * Represents a definition of an object of type [[A]] which are marked as @instantiable @@ -64,12 +65,12 @@ object Definition extends SourceInfoDoc { /** If this is an instance of a Module, returns the toTarget of this instance * @return target of this instance */ - def toTarget = d.proto.toTarget + def toTarget: ModuleTarget = d.proto.toTarget /** If this is an instance of a Module, returns the toAbsoluteTarget of this instance * @return absoluteTarget of this instance */ - def toAbsoluteTarget = d.proto.toAbsoluteTarget + def toAbsoluteTarget: IsModule = d.proto.toAbsoluteTarget } /** A construction method to build a Definition of a Module * diff --git a/core/src/main/scala/chisel3/experimental/hierarchy/Instance.scala b/core/src/main/scala/chisel3/experimental/hierarchy/Instance.scala index aec42da3..9b17bfce 100644 --- a/core/src/main/scala/chisel3/experimental/hierarchy/Instance.scala +++ b/core/src/main/scala/chisel3/experimental/hierarchy/Instance.scala @@ -4,11 +4,11 @@ package chisel3.experimental.hierarchy import scala.collection.mutable.{ArrayBuffer, HashMap} import scala.language.experimental.macros - import chisel3._ -import chisel3.internal.BaseModule.{ModuleClone, IsClone, InstantiableClone} +import chisel3.internal.BaseModule.{InstantiableClone, IsClone, ModuleClone} import chisel3.internal.sourceinfo.{InstanceTransform, SourceInfo} import chisel3.experimental.BaseModule +import firrtl.annotations.IsModule /** User-facing Instance type. * Represents a unique instance of type [[A]] which are marked as @instantiable @@ -75,15 +75,15 @@ object Instance extends SourceInfoDoc { /** If this is an instance of a Module, returns the toTarget of this instance * @return target of this instance */ - def toTarget = i.cloned match { - case Left(x: BaseModule) => x.toTarget - case Right(x: IsClone[_] with BaseModule) => x.toTarget + def toTarget: IsModule = i.cloned match { + case Left(x: BaseModule) => x.getTarget + case Right(x: IsClone[_] with BaseModule) => x.getTarget } /** If this is an instance of a Module, returns the toAbsoluteTarget of this instance * @return absoluteTarget of this instance */ - def toAbsoluteTarget = i.cloned match { + def toAbsoluteTarget: IsModule = i.cloned match { case Left(x) => x.toAbsoluteTarget case Right(x: IsClone[_] with BaseModule) => x.toAbsoluteTarget } diff --git a/core/src/main/scala/chisel3/internal/Builder.scala b/core/src/main/scala/chisel3/internal/Builder.scala index 1d15247d..441abc92 100644 --- a/core/src/main/scala/chisel3/internal/Builder.scala +++ b/core/src/main/scala/chisel3/internal/Builder.scala @@ -309,7 +309,7 @@ private[chisel3] trait NamedComponent extends HasId { val root = _parent.map { case ViewParent => reifyParent case other => other - }.get.toTarget // All NamedComponents will have a parent, only the top module can have None here + }.get.getTarget // All NamedComponents will have a parent, only the top module can have None here Target.toTargetTokens(name).toList match { case TargetToken.Ref(r) :: components => root.ref(r).copy(component = components) case other => -- cgit v1.2.3