aboutsummaryrefslogtreecommitdiff
path: root/src/main/stanza/chirrtl.stanza
blob: 43e6d2d6d238c1f09307ed32b3690fa1c822a385 (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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
;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.
defpackage firrtl/chirrtl :
   import core
   import verse
   import firrtl/ir2
   import firrtl/ir-utils
   import firrtl/primops


; ===============================
public val chirrtl-passes = to-list $ [
   CInferTypes()
   CInferMDir()
   RemoveCHIRRTL()
   FromCHIRRTL()
]
; ===============================


; CHIRRTL Additional IR Nodes
public definterface MPortDir
public val MInfer = new MPortDir
public val MRead = new MPortDir
public val MWrite = new MPortDir
public val MReadWrite = new MPortDir

defmethod print (o:OutputStream, m:MPortDir) :
   switch { m == _ } :
      MInfer : print(o,"infer")
      MRead : print(o,"read")
      MWrite : print(o,"write")
      MReadWrite : print(o,"rdwr")

public defstruct CDefMemory <: Stmt : ;LOW
   info: FileInfo with: (as-method => true)
   name: Symbol
   type: Type
   size: Int
   seq?: True|False
public defstruct CDefMPort <: Stmt :
   info: FileInfo with: (as-method => true)
   name: Symbol
   type: Type
   mem: Symbol
   exps: List<Expression>
   direction: MPortDir

defmethod print (o:OutputStream,c:CDefMemory) :
   if seq?(c) : print-all(o, ["smem " name(c) " : " type(c) "[" size(c) "]"])
   else : print-all(o, ["cmem " name(c) " : " type(c) "[" size(c) "]"])
defmethod map (f: Type -> Type, c:CDefMemory) -> CDefMemory :
   CDefMemory(info(c),name(c),f(type(c)),size(c),seq?(c))
defmethod map (f: Symbol -> Symbol, c:CDefMemory) -> CDefMemory :
   CDefMemory(info(c),f(name(c)),type(c),size(c),seq?(c))

defmethod print (o:OutputStream,c:CDefMPort) :
   print-all(o, [direction(c) " mport " name(c) " = " mem(c) "[" exps(c)[0] "], " exps(c)[1]])
defmethod map (f: Expression -> Expression, c:CDefMPort) -> CDefMPort :
   CDefMPort(info(c),name(c),type(c),mem(c),map(f,exps(c)),direction(c))
defmethod map (f: Type -> Type, c:CDefMPort) -> CDefMPort : 
   CDefMPort(info(c),name(c),f(type(c)),mem(c),exps(c),direction(c))
defmethod map (f: Symbol -> Symbol, c:CDefMPort) -> CDefMPort : 
   CDefMPort(info(c),f(name(c)),type(c),mem(c),exps(c),direction(c))


;======================= Infer Chirrtl Types ======================
public defstruct CInferTypes <: Pass
public defmethod pass (b:CInferTypes) -> (Circuit -> Circuit) : infer-types
public defmethod name (b:CInferTypes) -> String : "CInfer Types"
public defmethod short-name (b:CInferTypes) -> String : "cinfertypes"

;--------------- Utils -----------------

defn set-type (s:Stmt,t:Type) -> Stmt :
   match(s) :
      (s:DefWire) : DefWire(info(s),name(s),t)
      (s:DefRegister) : DefRegister(info(s),name(s),t,clock(s),reset(s),init(s))
      (s:CDefMemory) : CDefMemory(info(s),name(s),t,size(s),seq?(s))
      (s:CDefMPort) : CDefMPort(info(s),name(s),t,mem(s),exps(s),direction(s))
      (s:DefNode) : s
      (s:DefPoison) : DefPoison(info(s),name(s),t)

defn to-field (p:Port) -> Field :
   if direction(p) == OUTPUT : Field(name(p),DEFAULT,type(p))
   else if direction(p) == INPUT : Field(name(p),REVERSE,type(p))
   else : error("Shouldn't be here")
defn module-type (m:Module) -> Type : 
   BundleType(for p in ports(m) map : to-field(p))
defn field-type (v:Type,s:Symbol) -> Type :
   match(v) :
      (v:BundleType) : 
         val ft = for p in fields(v) find : name(p) == s
         if ft != false : type(ft as Field)
         else : UnknownType()
      (v) : UnknownType()
defn sub-type (v:Type) -> Type :
   match(v) :
      (v:VectorType) : type(v)
      (v) : UnknownType()

;--------------- Pass -----------------

defn infer-types (c:Circuit) -> Circuit :
   val module-types = HashTable<Symbol,Type>(symbol-hash)
   defn infer-types (m:Module) -> Module :
      val types = HashTable<Symbol,Type>(symbol-hash)
      defn infer-types-e (e:Expression) -> Expression :
         match(map(infer-types-e,e)) :
            (e:Ref) : Ref(name(e), get?(types,name(e),UnknownType()))
            (e:SubField) : SubField(exp(e),name(e),field-type(type(exp(e)),name(e)))
            (e:SubIndex) : SubIndex(exp(e),value(e),sub-type(type(exp(e))))
            (e:SubAccess) : SubAccess(exp(e),index(e),sub-type(type(exp(e))))
            (e:DoPrim) : set-primop-type(e)
            (e:Mux) : Mux(cond(e),tval(e),fval(e),mux-type(tval(e),tval(e)))
            (e:ValidIf) : ValidIf(cond(e),value(e),type(value(e)))
            (e:UIntValue|SIntValue) : e
      defn infer-types-s (s:Stmt) -> Stmt :
         match(s) :
            (s:DefRegister) : 
               types[name(s)] = type(s)
               map(infer-types-e,s)
               s
            (s:DefWire|DefPoison) : 
               types[name(s)] = type(s)
               s
            (s:DefNode) : 
               val s* = map(infer-types-e,s)
               val t = type(value(s*))
               types[name(s*)] = t
               s*
            (s:DefMemory) :
               types[name(s)] = get-type(s)
               s
            (s:CDefMPort) :
               val t = get?(types,mem(s),UnknownType())
               types[name(s)] = t
               CDefMPort(info(s),name(s),t,mem(s),exps(s),direction(s))
            (s:CDefMemory) :
               types[name(s)] = type(s)
               s
            (s:DefInstance) :
               types[name(s)] = get?(module-types,module(s),UnknownType())
               s
            (s) : map{infer-types-e,_} $ map(infer-types-s,s)
      for p in ports(m) do :
         types[name(p)] = type(p)
      match(m) :
         (m:InModule) :
            InModule(info(m),name(m),ports(m),infer-types-s(body(m)))
         (m:ExModule) : m

   ; MAIN
   for m in modules(c) do :
      module-types[name(m)] = module-type(m)
   Circuit{info(c), _, main(c) } $ 
      for m in modules(c) map :
         infer-types(m)

;==========================================

public defstruct CInferMDir <: Pass
public defmethod pass (b:CInferMDir) -> (Circuit -> Circuit) : infer-mdir
public defmethod name (b:CInferMDir) -> String : "CInfer MDir"
public defmethod short-name (b:CInferMDir) -> String : "cinfermdir"

defn infer-mdir (c:Circuit) -> Circuit :
   defn infer-mdir (m:Module) -> Module :
      val mports = HashTable<Symbol,MPortDir>(symbol-hash)
      defn infer-mdir-e (e:Expression,dir:MPortDir) -> Expression :
         match(map(infer-mdir-e{_,dir},e)) :
            (e:Ref) : 
               if key?(mports,name(e)) :
                  val new_mport_dir = 
                     switch fn ([x,y]) : mports[name(e)] == x and dir == y :
                        [MInfer,MInfer] : error("Shouldn't be here")
                        [MInfer,MWrite] : MWrite
                        [MInfer,MRead] : MRead
                        [MInfer,MReadWrite] : MReadWrite
                        [MWrite,MInfer] : error("Shouldn't be here")
                        [MWrite,MWrite] : MWrite
                        [MWrite,MRead] : MReadWrite
                        [MWrite,MReadWrite] : MReadWrite
                        [MRead,MInfer] : error("Shouldn't be here")
                        [MRead,MWrite] : MReadWrite
                        [MRead,MRead] : MRead
                        [MRead,MReadWrite] : MReadWrite
                        [MReadWrite,MInfer] : error("Shouldn't be here")
                        [MReadWrite,MWrite] : MReadWrite
                        [MReadWrite,MRead] : MReadWrite
                        [MReadWrite,MReadWrite] : MReadWrite
                  mports[name(e)] = new_mport_dir
               e
            (e) : e
      defn infer-mdir-s (s:Stmt) -> Stmt :
         match(s) :
            (s:CDefMPort) :
               mports[name(s)] = direction(s)
               map(infer-mdir-e{_,MRead},s)
            (s:Connect|BulkConnect) : 
               infer-mdir-e(exp(s),MRead)
               infer-mdir-e(loc(s),MWrite)
               s
            (s) : map{infer-mdir-e{_,MRead},_} $ map(infer-mdir-s,s)
      defn set-mdir-s (s:Stmt) -> Stmt :
         match(s) :
            (s:CDefMPort) : 
               CDefMPort(info(s),name(s),type(s),mem(s),exps(s),mports[name(s)])
            (s) : map(set-mdir-s,s)
      match(m) :
         (m:InModule) :
            infer-mdir-s(body(m))
            InModule(info(m),name(m),ports(m),set-mdir-s(body(m)))
         (m:ExModule) : m

   ; MAIN
   Circuit{info(c), _, main(c) } $ 
      for m in modules(c) map :
         infer-mdir(m)

;==========================================
public defstruct RemoveCHIRRTL <: Pass
public defmethod pass (b:RemoveCHIRRTL) -> (Circuit -> Circuit) : remove-chirrtl
public defmethod name (b:RemoveCHIRRTL) -> String : "Remove CHIRRTL"
public defmethod short-name (b:RemoveCHIRRTL) -> String : "removechirrtl"

defstruct MPort :
   name : Symbol
   clk : Expression
defstruct MPorts :
   readers : Vector<MPort>
   writers : Vector<MPort>
   readwriters : Vector<MPort>
defstruct DataRef :
   exp : Expression
   male : Symbol
   female : Symbol
   mask : Symbol
   rdwrite? : True|False

public definterface Gender
public val MALE = new Gender
public val FEMALE = new Gender

defn create-exps (e:Expression) -> List<Expression> :
   match(e) :
      (e:Mux) :
         for (e1 in create-exps(tval(e)), e2 in create-exps(fval(e))) map :
            Mux(cond(e),e1,e2,mux-type(e1,e2))
      (e:ValidIf) :
         for e1 in create-exps(value(e)) map :
            ValidIf(cond(e),e1,type(e1))
      (e) :
      match(type(e)) : 
         (t:UIntType|SIntType|ClockType) : list(e)
         (t:BundleType) : 
            for f in fields(t) map-append :
               create-exps(SubField(e,name(f),type(f)))
         (t:VectorType) :
            for i in 0 to size(t) map-append :
               create-exps(SubIndex(e,i,type(t)))
         (t:UnknownType) : list(e)

defn remove-chirrtl (c:Circuit) :
   defn remove-chirrtl-m (m:InModule) -> InModule :
      val hash = HashTable<Symbol,MPorts>(symbol-hash)
      val sh = get-sym-hash(m,keys(v-keywords))
      val repl = HashTable<Symbol,DataRef>(symbol-hash)
      val ut = UnknownType()
      val mport-types = HashTable<Symbol,Type>(symbol-hash)
      defn EMPs () -> MPorts : 
         MPorts(Vector<MPort>(),Vector<MPort>(),Vector<MPort>())
      defn collect-mports (s:Stmt) -> Stmt :
         match(s) :
            (s:CDefMPort) : 
               val mports = get?(hash,mem(s),EMPs())
               switch { _ == direction(s) } :
                  MRead : add(readers(mports),MPort(name(s),exps(s)[1]))
                  MWrite : add(writers(mports),MPort(name(s),exps(s)[1]))
                  MReadWrite : add(readwriters(mports),MPort(name(s),exps(s)[1]))
               hash[mem(s)] = mports
               s
            (s) : map(collect-mports,s)
      defn collect-refs (s:Stmt) -> Stmt :
         match(s) :
            (s:CDefMemory) :
               mport-types[name(s)] = type(s)
               val stmts = Vector<Stmt>()
               ;val naddr = firrtl-gensym(`GEN,sh)
               val taddr = UIntType(IntWidth(max(1,ceil-log2(size(s)))))
               ;add(stmts,DefPoison(info(s),naddr,taddr))
               ;val ndata = firrtl-gensym(`GEN,sh)
               val tdata = type(s)
               ;add(stmts,DefPoison(info(s),ndata,tdata))
               defn set-poison (vec:List<MPort>,addr:Symbol) -> False :
                  for r in vec do :
                     add(stmts,IsInvalid(info(s),SubField(SubField(Ref(name(s),ut),name(r),ut),addr,taddr)))
                     add(stmts,Connect(info(s),SubField(SubField(Ref(name(s),ut),name(r),ut),`clk,taddr),clk(r)))
               defn set-enable (vec:List<MPort>,en:Symbol) -> False:
                  for r in vec do :
                     add(stmts,Connect(info(s),SubField(SubField(Ref(name(s),ut),name(r),ut),en,taddr),zero))
               defn set-wmode (vec:List<MPort>,wmode:Symbol) -> False:
                  for r in vec do :
                     add(stmts,Connect(info(s),SubField(SubField(Ref(name(s),ut),name(r),ut),wmode,taddr),zero))
               defn set-write (vec:List<MPort>,data:Symbol,mask:Symbol) -> False :
                  val tmask = create-mask(type(s))
                  for r in vec do :
                     add(stmts,IsInvalid(info(s),SubField(SubField(Ref(name(s),ut),name(r),ut),data,tdata)))
                     for x in create-exps(SubField(SubField(Ref(name(s),ut),name(r),ut),mask,tmask)) do :
                        add(stmts,Connect(info(s),x,zero))
                        
               val rds = to-list $ readers $ get?(hash,name(s),EMPs())
               set-poison(rds,`addr)
               set-enable(rds,`en)
               val wrs = to-list $ writers $ get?(hash,name(s),EMPs())
               set-poison(wrs,`addr)
               set-enable(wrs,`en)
               set-write(wrs,`data,`mask)
               val rws = to-list $ readwriters $ get?(hash,name(s),EMPs())
               set-poison(rws,`addr)
               set-wmode(rws,`wmode)
               set-enable(rws,`en)
               set-write(rws,`data,`mask)
               val read-l = 
                  if seq?(s) : 1
                  else : 0
               val mem = DefMemory(info(s),name(s),type(s),size(s),1,read-l,map(name,rds),map(name,wrs),map(name,rws))
               Begin $ List(mem,to-list(stmts))
            (s:CDefMPort) :
               mport-types[name(s)] = mport-types[mem(s)]
               val addrs = Vector<Symbol>()
               val ens = Vector<Symbol>()
               val masks = Vector<Symbol>()
               switch { _ == direction(s) } :
                  MReadWrite : 
                     repl[name(s)] = DataRef(SubField(Ref(mem(s),ut),name(s),ut),`rdata,`data,`mask,true)
                     add(addrs,`addr)
                     add(ens,`en)
                     add(masks,`mask)
                  MWrite :
                     repl[name(s)] = DataRef(SubField(Ref(mem(s),ut),name(s),ut),`data,`data,`mask,false)
                     add(addrs,`addr)
                     add(ens,`en)
                     add(masks,`mask)
                  else :
                     repl[name(s)] = DataRef(SubField(Ref(mem(s),ut),name(s),ut),`data,`data,`blah,false)
                     add(addrs,`addr)
                     add(ens,`en)

               val stmts = Vector<Stmt>()
               for x in addrs do :
                  add(stmts,Connect(info(s),SubField(SubField(Ref(mem(s),ut),name(s),ut),x,ut),exps(s)[0]))
               for x in ens do :
                  add(stmts,Connect(info(s),SubField(SubField(Ref(mem(s),ut),name(s),ut),x,ut),one))
               Begin $ to-list $ stmts
            (s) : map(collect-refs,s)
      defn remove-chirrtl-s (s:Stmt) -> Stmt :
         var has-write-mport? = false
         var has-readwrite-mport? = false
         defn remove-chirrtl-e (e:Expression,g:Gender) -> Expression :
            match(e) :
               (e:Ref) : 
                  if key?(repl,name(e)) : 
                     val vt = repl[name(e)]
                     switch {g == _ }:
                        MALE : SubField(exp(vt),male(vt),type(e))
                        FEMALE : 
                           has-write-mport? = true
                           if rdwrite?(vt) == true :
                              has-readwrite-mport? = SubField(exp(vt),`wmode,UIntType(IntWidth(1)))
                           SubField(exp(vt),female(vt),type(e))
                  else : e
               (e:SubAccess) : SubAccess(remove-chirrtl-e(exp(e),g),remove-chirrtl-e(index(e),MALE),type(e))
               (e) : map(remove-chirrtl-e{_,g},e)
         defn get-mask (e:Expression) -> Expression :
            match(map(get-mask,e)) :
               (e:Ref) :
                  if key?(repl,name(e)) : 
                     val vt = repl[name(e)]
                     val t = create-mask(type(e))
                     SubField(exp(vt),mask(vt),t)
                  else : e
               (e) : e
         match(s) :
            (s:Connect) : 
               val stmts = Vector<Stmt>()
               val roc* = remove-chirrtl-e(exp(s),MALE)
               val loc* = remove-chirrtl-e(loc(s),FEMALE)
               add(stmts,Connect(info(s),loc*,roc*))
               if has-write-mport? :
                  val e = get-mask(loc(s))
                  for x in create-exps(e) do :
                     add(stmts,Connect(info(s),x,one))
                  if has-readwrite-mport? != false :
                     val wmode = has-readwrite-mport? as Expression
                     add(stmts,Connect(info(s),wmode,one))
               if length(stmts) > 1 : Begin(to-list(stmts))
               else : stmts[0]
            (s:BulkConnect) : 
               val stmts = Vector<Stmt>()
               val loc* = remove-chirrtl-e(loc(s),FEMALE)
               val roc* = remove-chirrtl-e(exp(s),MALE)
               add(stmts,BulkConnect(info(s),loc*,roc*))
               if has-write-mport? != false :
                  val ls = get-valid-points(type(loc(s)),type(exp(s)),DEFAULT,DEFAULT)
                  val locs = create-exps(get-mask(loc(s)))
                  for x in ls do :
                     val loc* = locs[x[0]]
                     add(stmts,Connect(info(s),loc*,one))
                  if has-readwrite-mport? != false :
                     val wmode = has-readwrite-mport? as Expression
                     add(stmts,Connect(info(s),wmode,one))
               if length(stmts) > 1 : Begin(to-list(stmts))
               else : stmts[0]
            (s) : map(remove-chirrtl-e{_,MALE}, map(remove-chirrtl-s,s))
      collect-mports(body(m))
      val s* = collect-refs(body(m))
      InModule(info(m),name(m), ports(m), remove-chirrtl-s(s*))
   Circuit(info(c),modules*, main(c)) where :
      val modules* =
         for m in modules(c) map :
            match(m) :
               (m:InModule) : remove-chirrtl-m(m)
               (m:ExModule) : m


;============ FromCHIRRTL ==============

public defstruct FromCHIRRTL <: Pass
public defmethod pass (b:FromCHIRRTL) -> (Circuit -> Circuit) : from-chirrtl
public defmethod name (b:FromCHIRRTL) -> String : "From CHIRRTL"
public defmethod short-name (b:FromCHIRRTL) -> String : "from-chirrtl"

defn from-chirrtl (c:Circuit) -> Circuit :
   val c1 = infer-types(c)
   ;println(c1)
   val c2 = infer-mdir(c1)
   ;println(c2)
   val c3 = remove-chirrtl(c2)
   ;println(c3)
   c3