summaryrefslogtreecommitdiff
path: root/core/src/main/scala/chisel3/Mux.scala
blob: 3ec0d6aba372957dee19c7a41c40ec9c32e30e05 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// SPDX-License-Identifier: Apache-2.0

package chisel3

import chisel3.internal._
import chisel3.internal.Builder.pushOp
import chisel3.internal.firrtl._
import chisel3.internal.firrtl.PrimOp._

object Mux {

  /** Creates a mux, whose output is one of the inputs depending on the
    * value of the condition.
    *
    * @param cond condition determining the input to choose
    * @param con the value chosen when `cond` is true
    * @param alt the value chosen when `cond` is false
    * @example
    * {{{
    * val muxOut = Mux(data_in === 3.U, 3.U(4.W), 0.U(4.W))
    * }}}
    */
  def apply[T <: Data](
    cond: Bool,
    con:  T,
    alt:  T
  ): T = {
    requireIsHardware(cond, "mux condition")
    requireIsHardware(con, "mux true value")
    requireIsHardware(alt, "mux false value")
    val d = cloneSupertype(Seq(con, alt), "Mux")
    val conRef = con match { // this matches chisel semantics (DontCare as object) to firrtl semantics (invalidate)
      case DontCare =>
        val dcWire = Wire(d)
        dcWire := DontCare
        dcWire.ref
      case _ => con.ref
    }
    val altRef = alt match {
      case DontCare =>
        val dcWire = Wire(d)
        dcWire := DontCare
        dcWire.ref
      case _ => alt.ref
    }
    pushOp(DefPrim(d, MultiplexOp, cond.ref, conRef, altRef))
  }
}