aboutsummaryrefslogtreecommitdiff
path: root/src/main/scala/firrtl/passes/ExpandWhens.scala
blob: d68b1eaa780014890791099239e580e1dbc3f572 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
/*
Copyright (c) 2014 - 2016 The Regents of the University of
California (Regents). All Rights Reserved.  Redistribution and use in
source and binary forms, with or without modification, are permitted
provided that the following conditions are met:
   * Redistributions of source code must retain the above
     copyright notice, this list of conditions and the following
     two paragraphs of disclaimer.
   * Redistributions in binary form must reproduce the above
     copyright notice, this list of conditions and the following
     two paragraphs of disclaimer in the documentation and/or other materials
     provided with the distribution.
   * Neither the name of the Regents nor the names of its contributors
     may be used to endorse or promote products derived from this
     software without specific prior written permission.
IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
REGENTS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF
ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION
TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.
*/

package firrtl.passes

import firrtl._
import firrtl.Utils._
import firrtl.Mappers._
import firrtl.PrimOps._
import firrtl.WrappedExpression._

// Datastructures
import scala.collection.mutable.HashMap
import scala.collection.mutable.LinkedHashMap
import scala.collection.mutable.ArrayBuffer

import annotation.tailrec

/** Expand Whens
*
* @note This pass does three things: remove last connect semantics,
* remove conditional blocks, and eliminate concept of scoping.
* @note Assumes bulk connects and isInvalids have been expanded
* @note Assumes all references are declared
*/
object ExpandWhens extends Pass {
  def name = "Expand Whens"

  // ========== Expand When Utilz ==========
  private def getEntries(
      hash: LinkedHashMap[WrappedExpression, Expression],
      exps: Seq[Expression]): LinkedHashMap[WrappedExpression, Expression] = {
    val hashx = LinkedHashMap[WrappedExpression, Expression]()
    exps foreach (e => if (hash.contains(e)) hashx(e) = hash(e))
    hashx
  }
  private def getFemaleRefs(n: String, t: Type, g: Gender): Seq[Expression] = {
    def getGender(t: Type, i: Int, g: Gender): Gender = times(g, get_flip(t, i, DEFAULT))
    val exps = create_exps(WRef(n, t, ExpKind(), g))
    val expsx = ArrayBuffer[Expression]()
    for (j <- 0 until exps.size) {
      getGender(t, j, g) match {
        case (BIGENDER | FEMALE) => expsx += exps(j)
        case _ =>
      }
    }
    expsx
  }
  private def squashEmpty(s: Stmt): Stmt = {
    s map squashEmpty match {
      case Begin(stmts) =>
        val newStmts = stmts filter (_ != Empty())
        newStmts.size match {
          case 0 => Empty()
          case 1 => newStmts.head
          case _ => Begin(newStmts)
        }
      case s => s
    }
  }
  private def expandNetlist(netlist: LinkedHashMap[WrappedExpression, Expression]) =
    netlist map { case (k, v) =>
      v match {
        case WInvalid() => IsInvalid(NoInfo, k.e1)
        case _ => Connect(NoInfo, k.e1, v)
      }
    }
  // Searches nested scopes of defaults for lvalue
  // defaults uses mutable Map because we are searching LinkedHashMaps and conversion to immutable is VERY slow
  @tailrec
  private def getDefault(
      lvalue: WrappedExpression, 
      defaults: Seq[collection.mutable.Map[WrappedExpression, Expression]]): Option[Expression] = {
    if (defaults.isEmpty) None
    else if (defaults.head.contains(lvalue)) defaults.head.get(lvalue)
    else getDefault(lvalue, defaults.tail)
  }

  // ------------ Pass -------------------
  def run(c: Circuit): Circuit = {
    def expandWhens(m: Module): (LinkedHashMap[WrappedExpression, Expression], ArrayBuffer[Stmt], Stmt) = {
      val namespace = Namespace(m)
      val simlist = ArrayBuffer[Stmt]()

      // defaults ideally would be immutable.Map but conversion from mutable.LinkedHashMap to mutable.Map is VERY slow
      def expandWhens(
          netlist: LinkedHashMap[WrappedExpression, Expression],
          defaults: Seq[collection.mutable.Map[WrappedExpression, Expression]],
          p: Expression)
          (s: Stmt): Stmt = {
        s match {
          case w: DefWire =>
            getFemaleRefs(w.name, w.tpe, BIGENDER) foreach (ref => netlist(ref) = WVoid())
            w
          case r: DefRegister =>
            getFemaleRefs(r.name, r.tpe, BIGENDER) foreach (ref => netlist(ref) = ref)
            r
          case c: Connect =>
            netlist(c.loc) = c.exp
            Empty()
          case c: IsInvalid =>
            netlist(c.exp) = WInvalid()
            Empty()
          case s: Conditionally =>
            val memos = ArrayBuffer[Stmt]()

            val conseqNetlist = LinkedHashMap[WrappedExpression, Expression]()
            val altNetlist = LinkedHashMap[WrappedExpression, Expression]()
            val conseqStmt = expandWhens(conseqNetlist, netlist +: defaults, AND(p, s.pred))(s.conseq)
            val altStmt = expandWhens(altNetlist, netlist +: defaults, AND(p, NOT(s.pred)))(s.alt)

            (conseqNetlist.keySet ++ altNetlist.keySet) foreach { lvalue =>
              // Defaults in netlist get priority over those in defaults
              val default = if (netlist.contains(lvalue)) netlist.get(lvalue) else getDefault(lvalue, defaults)
              val res = default match {
                case Some(defaultValue) =>
                  val trueValue = conseqNetlist.getOrElse(lvalue, defaultValue)
                  val falseValue = altNetlist.getOrElse(lvalue, defaultValue)
                  (trueValue, falseValue) match {
                    case (WInvalid(), WInvalid()) => WInvalid()
                    case (WInvalid(), fv) => ValidIf(NOT(s.pred), fv, tpe(fv))
                    case (tv, WInvalid()) => ValidIf(s.pred, tv, tpe(tv))
                    case (tv, fv) => Mux(s.pred, tv, fv, mux_type_and_widths(tv, fv))
                  }
                case None =>
                  // Since not in netlist, lvalue must be declared in EXACTLY one of conseq or alt
                  conseqNetlist.getOrElse(lvalue, altNetlist(lvalue))
              }

              val memoNode = DefNode(s.info, namespace.newTemp, res)
              val memoExpr = WRef(memoNode.name, res.tpe, NodeKind(), MALE)
              memos += memoNode
              netlist(lvalue) = memoExpr
            }
            Begin(Seq(conseqStmt, altStmt) ++ memos)

          case s: Print =>
            if(weq(p, one)) {
              simlist += s
            } else {
              simlist += Print(s.info, s.string, s.args, s.clk, AND(p, s.en))
            }
            Empty()
          case s: Stop =>
            if (weq(p, one)) {
              simlist += s
            } else {
              simlist += Stop(s.info, s.ret, s.clk, AND(p, s.en))
            }
            Empty()
          case s => s map expandWhens(netlist, defaults, p)
        }
      }
      val netlist = LinkedHashMap[WrappedExpression, Expression]()

      // Add ports to netlist
      m.ports foreach { port =>
        getFemaleRefs(port.name, port.tpe, to_gender(port.direction)) foreach (ref => netlist(ref) = WVoid())
      }
      val bodyx = expandWhens(netlist, Seq(netlist), one)(m.body)

      (netlist, simlist, bodyx)
    }
    val modulesx = c.modules map { m =>
      m match {
        case m: ExtModule => m
        case m: Module =>
        val (netlist, simlist, bodyx) = expandWhens(m)
        val newBody = Begin(Seq(bodyx map squashEmpty) ++ expandNetlist(netlist) ++ simlist)
        Module(m.info, m.name, m.ports, newBody)
      }
    }
    Circuit(c.info, modulesx, c.main)
  }
}