WARNING! Access to this system is limited to authorised users only.
Unauthorised users may be subject to prosecution.
Unauthorised access to this system is a criminal offence under Australian law (Federal Crimes Act 1914 Part VIA)
It is a criminal offence to:
(1) Obtain access to data without authority. -Penalty 2 years imprisonment.
(2) Damage, delete, alter or insert data without authority. -Penalty 10 years imprisonment.
User activity is monitored and recorded. Anyone using this system expressly consents to such monitoring and recording.

To protect your data, the CISO officer has suggested users to enable 2FA as soon as possible.
Currently 2.7% of users enabled 2FA.

UIRTextReader.scala 26.8 KB
Newer Older
Kunshan Wang's avatar
Kunshan Wang committed
1
2
3
4
package uvm.ir.textinput

import org.antlr.v4.runtime._
import org.antlr.v4.runtime.tree.TerminalNode
Kunshan Wang's avatar
Kunshan Wang committed
5
import uvm._
Kunshan Wang's avatar
Kunshan Wang committed
6
import uvm.comminsts.CommInsts
Kunshan Wang's avatar
Kunshan Wang committed
7
8
9
10
11
import uvm.ir.textinput.gen.UIRParser._
import uvm.ir.textinput.gen._
import uvm.ssavariables._
import uvm.types._
import scala.collection.JavaConversions._
Kunshan Wang's avatar
Kunshan Wang committed
12
import scala.collection.mutable.ArrayBuffer
13
14
15
import scala.collection.immutable.Stream
import java.io.StringWriter
import java.nio.CharBuffer
Kunshan Wang's avatar
Kunshan Wang committed
16

Kunshan Wang's avatar
Kunshan Wang committed
17
class UIRTextReader(val idFactory: IDFactory) {
Kunshan Wang's avatar
Kunshan Wang committed
18
  import UIRTextReader._
Kunshan Wang's avatar
Kunshan Wang committed
19
  import uvm.ir.textinput.Later.Laterable
Kunshan Wang's avatar
Kunshan Wang committed
20

Kunshan Wang's avatar
Kunshan Wang committed
21
  def read(ir: String, globalBundle: GlobalBundle): TrantientBundle = {
Kunshan Wang's avatar
Kunshan Wang committed
22
    val input = new ANTLRInputStream(ir)
23
    read(ir, input, globalBundle)
Kunshan Wang's avatar
Kunshan Wang committed
24
25
  }

Kunshan Wang's avatar
Kunshan Wang committed
26
  def read(ir: java.io.Reader, globalBundle: GlobalBundle): TrantientBundle = {
27
28
29
30
31
32
33
34
35
36
37
38
39
40
    val sb = new StringBuilder()
    val cb = new Array[Char](4096)

    var finished = false
    while (!finished) {
      val actualRead = ir.read(cb, 0, 4096)
      if (actualRead > 0) {
        sb.appendAll(cb, 0, actualRead)
      } else {
        finished = true
      }
    }

    read(sb.toString(), globalBundle)
Kunshan Wang's avatar
Kunshan Wang committed
41
42
  }

43
  class AccumulativeAntlrErrorListener(source: String) extends BaseErrorListener {
Kunshan Wang's avatar
Kunshan Wang committed
44
45
    val buf = new ArrayBuffer[String]()
    var hasError = false
46
47
48

    lazy val sourceLines = ArrayBuffer(source.lines.toSeq: _*)

Kunshan Wang's avatar
Kunshan Wang committed
49
    override def syntaxError(recognizer: Recognizer[_, _], offendingSymbol: Object,
50
                             line: Int, charPositionInLine: Int, msg: String, e: RecognitionException): Unit = {
51
52
53
      val theLine = sourceLines(line - 1)
      val marker = " " * charPositionInLine + "^"
      buf.add("line %d:%d %s\n%s\n%s".format(line, charPositionInLine, msg, theLine, marker))
Kunshan Wang's avatar
Kunshan Wang committed
54
55
      hasError = true
    }
56

Kunshan Wang's avatar
Kunshan Wang committed
57
58
59
    def getMessages(): String = buf.mkString("\n")
  }

Kunshan Wang's avatar
Kunshan Wang committed
60
  def read(source: String, ais: ANTLRInputStream, globalBundle: GlobalBundle): TrantientBundle = {
61
62
63
64
65
    val ea = new AccumulativeAntlrErrorListener(source)

    val lexer = new UIRLexer(ais)
    lexer.removeErrorListeners()
    lexer.addErrorListener(ea)
Kunshan Wang's avatar
Kunshan Wang committed
66
67
    val tokens = new CommonTokenStream(lexer)
    val parser = new UIRParser(tokens)
Kunshan Wang's avatar
Kunshan Wang committed
68
69
    parser.removeErrorListeners()
    parser.addErrorListener(ea)
Kunshan Wang's avatar
Kunshan Wang committed
70
    val ast = parser.ir()
Kunshan Wang's avatar
Kunshan Wang committed
71
    if (ea.hasError) {
72
      throw new TextIRParsingException("Syntax error:\n" + ea.getMessages)
Kunshan Wang's avatar
Kunshan Wang committed
73
    }
Kunshan Wang's avatar
Kunshan Wang committed
74
    read(ast, globalBundle)
Kunshan Wang's avatar
Kunshan Wang committed
75

Kunshan Wang's avatar
Kunshan Wang committed
76
77
78
  }

  implicit def terminalToString(tn: TerminalNode): String = tn.getText()
Kunshan Wang's avatar
Kunshan Wang committed
79
80
81
82
  implicit def nameToString(name: NameContext): String = name.getText()
  implicit def tokenToString(tok: Token): String = tok.getText()

  val IntRe = """([+-]?)(0x|0|)([0-9a-fA-F]*)""".r
Kunshan Wang's avatar
Kunshan Wang committed
83
84
85

  implicit def IntLiteralToBigInt(il: IntLiteralContext): BigInt = {
    val txt = il.getText()
Kunshan Wang's avatar
Kunshan Wang committed
86
87
88
89
90
91

    txt match {
      case IntRe(sign, prefix, nums) => {
        val neg = sign match {
          case "+" => false
          case "-" => true
92
          case ""  => false
Kunshan Wang's avatar
Kunshan Wang committed
93
94
95
        }
        val abs = prefix match {
          case "0x" => BigInt(nums, 16)
96
97
          case "0"  => if (nums == "") BigInt(0) else BigInt(nums, 8)
          case ""   => BigInt(nums, 10)
Kunshan Wang's avatar
Kunshan Wang committed
98
99
100
        }
        return if (neg) -abs else abs
      }
Kunshan Wang's avatar
Kunshan Wang committed
101
102
103
104
    }
  }

  implicit def floatLiteralToFloat(fl: FloatLiteralContext): Float = fl match {
Kunshan Wang's avatar
Kunshan Wang committed
105
106
107
    case num: FloatNumberContext => num.FP_NUM.getText.toFloat
    case fi: FloatInfContext => {
      if (fi.getText.startsWith("-"))
Kunshan Wang's avatar
Kunshan Wang committed
108
        java.lang.Float.NEGATIVE_INFINITY
Kunshan Wang's avatar
Kunshan Wang committed
109
      else java.lang.Float.POSITIVE_INFINITY
Kunshan Wang's avatar
Kunshan Wang committed
110
    }
111
    case _: FloatNanContext     => java.lang.Float.NaN
Kunshan Wang's avatar
Kunshan Wang committed
112
    case bits: FloatBitsContext => java.lang.Float.intBitsToFloat(bits.intLiteral().intValue())
Kunshan Wang's avatar
Kunshan Wang committed
113
  }
Kunshan Wang's avatar
Kunshan Wang committed
114

Kunshan Wang's avatar
Kunshan Wang committed
115
  implicit def doubleLiteralToDouble(dl: DoubleLiteralContext): Double = dl match {
Kunshan Wang's avatar
Kunshan Wang committed
116
117
118
    case num: DoubleNumberContext => num.FP_NUM.getText.toDouble
    case fi: DoubleInfContext => {
      if (fi.getText.startsWith("-"))
Kunshan Wang's avatar
Kunshan Wang committed
119
        java.lang.Double.NEGATIVE_INFINITY
Kunshan Wang's avatar
Kunshan Wang committed
120
      else java.lang.Double.POSITIVE_INFINITY
Kunshan Wang's avatar
Kunshan Wang committed
121
    }
122
    case _: DoubleNanContext     => java.lang.Double.NaN
Kunshan Wang's avatar
Kunshan Wang committed
123
    case bits: DoubleBitsContext => java.lang.Double.longBitsToDouble(bits.intLiteral().longValue())
Kunshan Wang's avatar
Kunshan Wang committed
124
125
  }

Kunshan Wang's avatar
Kunshan Wang committed
126
  def cascadeLookup[T <: Identified](name: String, ns1: Namespace[T], ns2: Namespace[T]): T =
Kunshan Wang's avatar
Kunshan Wang committed
127
    ns1.get(name).getOrElse(ns2(name))
Kunshan Wang's avatar
Kunshan Wang committed
128

Kunshan Wang's avatar
Kunshan Wang committed
129
130
131
132
133
134
135
136
137
138
139
140
  // Printing context information (line, column, near some token)

  def inCtx(ctx: ParserRuleContext, s: String): String = nearTok(ctx.getStart, s)
  def inCtx(ctx: TerminalNode, s: String): String = nearTok(ctx.getSymbol, s)

  def nearTok(tok: Token, s: String): String = {
    val line = tok.getLine()
    val column = tok.getCharPositionInLine()
    val near = tok.getText()
    return "At %d:%d near '%s': %s".format(line, column, near, s)
  }

Kunshan Wang's avatar
Kunshan Wang committed
141
142
143
144
145
146
  def catchIn[T](ctx: ParserRuleContext, s: String)(func: => T): T = try {
    func
  } catch {
    case e: Exception => throw new TextIRParsingException(inCtx(ctx, s), e)
  }

Kunshan Wang's avatar
Kunshan Wang committed
147
148
  def read(ir: IrContext, globalBundle: GlobalBundle): TrantientBundle = {
    val bundle = new TrantientBundle()
Kunshan Wang's avatar
Kunshan Wang committed
149

Kunshan Wang's avatar
Kunshan Wang committed
150
    // Resolve global entities. (If any resXxxx is not present, that's because it is simply not currently used)
Kunshan Wang's avatar
Kunshan Wang committed
151

Kunshan Wang's avatar
Kunshan Wang committed
152
    implicit def resTy(ctx: TypeContext): Type = catchIn(ctx, "Unable to resolve type") { resTyByName(ctx.getText) }
Kunshan Wang's avatar
Kunshan Wang committed
153
    def resTyByName(name: String): Type = cascadeLookup(name, bundle.typeNs, globalBundle.typeNs)
Kunshan Wang's avatar
Kunshan Wang committed
154

Kunshan Wang's avatar
Kunshan Wang committed
155
    implicit def resSig(ctx: FuncSigContext): FuncSig = catchIn(ctx, "Unable to resolve sig") { resSigByName(ctx.getText) }
Kunshan Wang's avatar
Kunshan Wang committed
156
    def resSigByName(name: String): FuncSig = cascadeLookup(name, bundle.funcSigNs, globalBundle.funcSigNs)
Kunshan Wang's avatar
Kunshan Wang committed
157

Kunshan Wang's avatar
Kunshan Wang committed
158
    implicit def resConst(ctx: ConstantContext): Constant = catchIn(ctx, "Unable to resolve const") { resConstByName(ctx.getText) }
Kunshan Wang's avatar
Kunshan Wang committed
159
    def resConstByName(name: String): Constant = cascadeLookup(name, bundle.constantNs, globalBundle.constantNs)
Kunshan Wang's avatar
Kunshan Wang committed
160
161

    def resGlobalVar(name: String): GlobalVariable = cascadeLookup(name, bundle.globalVarNs, globalBundle.globalVarNs)
162
163
164
165
    def resFunc(name: String): Function = cascadeLookup(name, bundle.funcNs, globalBundle.funcNs)

    implicit def convFlag(f: FlagContext): Flag = Flag(f.FLAG().getText)
    implicit def convFlagList(a: FlagListContext): Seq[Flag] = a.flag().map(convFlag)
Kunshan Wang's avatar
Kunshan Wang committed
166

Kunshan Wang's avatar
Kunshan Wang committed
167
168
169
170
171
172
173
174
175
176
177
178
179
180
    // Resolve global entities from special structures.
    implicit def resTypeList(a: TypeListContext): Seq[Type] = a.`type`.map(resTy)
    implicit def resFuncSigList(a: FuncSigListContext): Seq[FuncSig] = a.funcSig().map(resSig)

    // Resolve special structures

    implicit def resOrd(ord: MemordContext): MemoryOrder.Value = {
      if (ord == null) {
        MemoryOrder.NOT_ATOMIC
      } else {
        MemoryOrder.withName(ord.getText)
      }
    }

Kunshan Wang's avatar
Kunshan Wang committed
181
182
    // Add entities to namespaces.

183
    def addTy(obj: Type): Unit = {
Kunshan Wang's avatar
Kunshan Wang committed
184
      bundle.typeNs.add(obj)
185
186
    }
    def addSig(obj: FuncSig): Unit = {
Kunshan Wang's avatar
Kunshan Wang committed
187
188
189
190
      bundle.funcSigNs.add(obj)
    }
    def addFuncVer(obj: FuncVer): Unit = {
      bundle.funcVerNs.add(obj)
191
    }
Kunshan Wang's avatar
Kunshan Wang committed
192
    def addConst(obj: Constant): Unit = {
Kunshan Wang's avatar
Kunshan Wang committed
193
      bundle.constantNs.add(obj)
Kunshan Wang's avatar
Kunshan Wang committed
194
195
    }
    def addGlobalCell(obj: GlobalCell): Unit = {
Kunshan Wang's avatar
Kunshan Wang committed
196
      bundle.globalCellNs.add(obj)
Kunshan Wang's avatar
Kunshan Wang committed
197
198
    }
    def addFunc(obj: Function): Unit = {
Kunshan Wang's avatar
Kunshan Wang committed
199
      bundle.funcNs.add(obj)
Kunshan Wang's avatar
Kunshan Wang committed
200
    }
201
    def addExpFunc(obj: ExposedFunc): Unit = {
Kunshan Wang's avatar
Kunshan Wang committed
202
      bundle.expFuncNs.add(obj)
Kunshan Wang's avatar
Kunshan Wang committed
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
    }

    // Resolve types, with parse-time checking.

    def needType[E <: Type](tc: TypeContext, expectedType: Class[E], n: String): E = {
      val t = resTy(tc)
      if (!(expectedType.isAssignableFrom(t.getClass))) {
        throw new UnexpectedTypeException(inCtx(tc, "Expected %s, actually %s.".format(n, t)))
      }
      t.asInstanceOf[E]
    }

    def needInt[T <: Type](tc: TypeContext) = needType(tc, classOf[TypeInt], "int")
    def needStruct[T <: Type](tc: TypeContext) = needType(tc, classOf[TypeStruct], "struct")
    def needArray[T <: Type](tc: TypeContext) = needType(tc, classOf[TypeArray], "array")
    def needVector[T <: Type](tc: TypeContext) = needType(tc, classOf[TypeVector], "vector")
    def needHybrid[T <: Type](tc: TypeContext) = needType(tc, classOf[TypeHybrid], "hybrid")
Kunshan Wang's avatar
Kunshan Wang committed
220
    def needSeq[T <: Type](tc: TypeContext) = needType(tc, classOf[AbstractSeqType], "array or vector")
Kunshan Wang's avatar
Kunshan Wang committed
221

222
223
224
225
226
227
228
229
    def needConstInt64(ctx: ParserRuleContext, name: String): ConstInt = {
      val c = resConstByName(name)
      if (!c.isInstanceOf[ConstInt]) {
        throw new UnexpectedTypeException(inCtx(ctx, "Expected 64-bit integer constant, actually %s.".format(c.getClass)))
      }
      c.asInstanceOf[ConstInt]
    }

Kunshan Wang's avatar
Kunshan Wang committed
230
231
    // Make types and sigs

Kunshan Wang's avatar
Kunshan Wang committed
232
    val phase1 = new Later() // Resolve inter-references between types and sigs
Kunshan Wang's avatar
Kunshan Wang committed
233

Kunshan Wang's avatar
Kunshan Wang committed
234
235
    def mkType(tc: TypeConstructorContext): Type = {
      val ty = tc match {
Kunshan Wang's avatar
Kunshan Wang committed
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
        case t: TypeIntContext       => TypeInt(t.length.intValue())
        case t: TypeFloatContext     => TypeFloat()
        case t: TypeDoubleContext    => TypeDouble()
        case t: TypeRefContext       => TypeRef(null).later(phase1) { _.ty = t.ty }
        case t: TypeIRefContext      => TypeIRef(null).later(phase1) { _.ty = t.ty }
        case t: TypeWeakRefContext   => TypeWeakRef(null).later(phase1) { _.ty = t.ty }
        case t: TypeStructContext    => TypeStruct(null).later(phase1) { _.fieldTys = t.fieldTys.map(resTy)}
        case t: TypeArrayContext     => TypeArray(null, t.length.longValue()).later(phase1) { _.elemTy = t.ty }
        case t: TypeHybridContext    => TypeHybrid(null, null).later(phase1) { tt => tt.fixedTy = t.fixedTy; tt.varTy = t.varTy }
        case t: TypeVoidContext      => TypeVoid()
        case t: TypeFuncRefContext   => TypeFuncRef(null).later(phase1) { _.sig = t.funcSig() }
        case t: TypeThreadRefContext => TypeThreadRef()
        case t: TypeStackRefContext  => TypeStackRef()
        case t: TypeTagRef64Context  => TypeTagRef64()
        case t: TypeVectorContext    => TypeVector(null, t.length.longValue()).later(phase1) { _.elemTy = t.ty }
        case t: TypeUPtrContext      => TypeUPtr(null).later(phase1) { _.ty = t.ty }
        case t: TypeUFuncPtrContext  => TypeUFuncPtr(null).later(phase1) { _.sig = t.funcSig }
        case _                       => throw new TextIRParsingException("foo")
Kunshan Wang's avatar
Kunshan Wang committed
254
255
256
257
258
259
      }
      return ty
    }

    def mkSig(fsc: FuncSigConstructorContext): FuncSig = {
      val sig = FuncSig(null, null).later(phase1) { sig =>
Kunshan Wang's avatar
Kunshan Wang committed
260
        sig.retTy = resTy(fsc.retTy)
Kunshan Wang's avatar
Kunshan Wang committed
261
        sig.paramTy = for (t <- fsc.paramTys) yield resTy(t)
Kunshan Wang's avatar
Kunshan Wang committed
262
263
264
265
      }
      return sig
    }

Kunshan Wang's avatar
Kunshan Wang committed
266
    ir.topLevelDef.map(_.getChild(0)).foreach {
Kunshan Wang's avatar
Kunshan Wang committed
267
268
      case td: TypeDefContext => {
        val ty = mkType(td.typeConstructor)
Kunshan Wang's avatar
Kunshan Wang committed
269
270
        ty.id = idFactory.getID()
        ty.name = Some(td.nam)
Kunshan Wang's avatar
Kunshan Wang committed
271
        addTy(ty)
Kunshan Wang's avatar
Kunshan Wang committed
272
273
274
      }
      case fsd: FuncSigDefContext => {
        val sig = mkSig(fsd.funcSigConstructor)
Kunshan Wang's avatar
Kunshan Wang committed
275
276
        sig.id = idFactory.getID()
        sig.name = Some(fsd.nam)
Kunshan Wang's avatar
Kunshan Wang committed
277
        addSig(sig)
Kunshan Wang's avatar
Kunshan Wang committed
278
      }
Kunshan Wang's avatar
Kunshan Wang committed
279
      case _ =>
Kunshan Wang's avatar
Kunshan Wang committed
280
281
282
283
    }

    phase1.doAll()

Kunshan Wang's avatar
Kunshan Wang committed
284
    val phase2 = new Later() // Resolve inter-references from constants to other global variables
Kunshan Wang's avatar
Kunshan Wang committed
285

Kunshan Wang's avatar
Kunshan Wang committed
286
    def mkConst(t: Type, c: ConstConstructorContext): Constant = {
Kunshan Wang's avatar
Kunshan Wang committed
287
      val con = c match {
Kunshan Wang's avatar
Kunshan Wang committed
288
        case cc: CtorIntContext => t match {
289
290
291
          case _: TypeInt             => ConstInt(t, cc.intLiteral)
          case _: AbstractPointerType => ConstPointer(t, cc.intLiteral().longValue())
        }
Kunshan Wang's avatar
Kunshan Wang committed
292
293
294
295
296
297
298
299
300
301
302
303
        case cc: CtorFloatContext  => ConstFloat(t, cc.floatLiteral)
        case cc: CtorDoubleContext => ConstDouble(t, cc.doubleLiteral)
        case cc: CtorListContext => t match {
          case _: TypeStruct => ConstStruct(t, null).later(phase2) {
            _.fields = for (gn <- cc.GLOBAL_NAME()) yield resGlobalVar(gn)
          }
          case _: TypeArray => ConstArray(t, null).later(phase2) {
            _.elems = for (gn <- cc.GLOBAL_NAME()) yield resGlobalVar(gn)
          }
          case _: TypeVector => ConstVector(t, null).later(phase2) {
            _.elems = for (c <- cc.GLOBAL_NAME()) yield resConstByName(c)
          }
Kunshan Wang's avatar
Kunshan Wang committed
304
        }
Kunshan Wang's avatar
Kunshan Wang committed
305
        case _: CtorNullContext => ConstNull(t)
Kunshan Wang's avatar
Kunshan Wang committed
306
307
308
309
      }
      return con
    }

Kunshan Wang's avatar
Kunshan Wang committed
310
    def mkGlobalCell(t: Type): GlobalCell = GlobalCell(t)
Kunshan Wang's avatar
Kunshan Wang committed
311
312
313
314
315
316
317

    def mkFunc(sig: FuncSig): Function = {
      val func = new Function()
      func.sig = sig
      return func
    }

Kunshan Wang's avatar
Kunshan Wang committed
318
    def mkExpo(c: FuncExpDefContext): ExposedFunc = {
319
320
321
322
323
324
325
      val efun = ExposedFunc(null, c.callConv, null).later(phase2) { ee =>
        ee.func = resFunc(c.funcName)
        ee.cookie = needConstInt64(c, c.cookie)
      }
      return efun
    }

Kunshan Wang's avatar
Kunshan Wang committed
326
327
    def findOldFunc(name: String): Option[Function] = {
      globalBundle.funcNs.get(name)
Kunshan Wang's avatar
Kunshan Wang committed
328
329
330
331
332
    }

    def declFunc(n: String, s: FuncSigContext): Function = {
      val sig = resSig(s)
      val func = mkFunc(sig)
Kunshan Wang's avatar
Kunshan Wang committed
333
      func.id = idFactory.getID()
Kunshan Wang's avatar
Kunshan Wang committed
334
      func.name = Some(n)
Kunshan Wang's avatar
Kunshan Wang committed
335
      addFunc(func)
Kunshan Wang's avatar
Kunshan Wang committed
336

Kunshan Wang's avatar
Kunshan Wang committed
337
      func
Kunshan Wang's avatar
Kunshan Wang committed
338
339
    }

Kunshan Wang's avatar
Kunshan Wang committed
340
    val funcDefs = new ArrayBuffer[(Function, FuncDefContext)]
Kunshan Wang's avatar
Kunshan Wang committed
341

Kunshan Wang's avatar
Kunshan Wang committed
342
    ir.topLevelDef().map(_.getChild(0)).foreach {
Kunshan Wang's avatar
Kunshan Wang committed
343
      case cdctx: ConstDefContext => {
Kunshan Wang's avatar
Kunshan Wang committed
344
        val ty = resTy(cdctx.ty)
Kunshan Wang's avatar
Kunshan Wang committed
345
346
347
        val con = mkConst(ty, cdctx.constConstructor)
        con.id = idFactory.getID()
        con.name = Some(cdctx.nam)
Kunshan Wang's avatar
Kunshan Wang committed
348
        addConst(con)
Kunshan Wang's avatar
Kunshan Wang committed
349
350
      }
      case gdctx: GlobalDefContext => {
Kunshan Wang's avatar
Kunshan Wang committed
351
        val ty = resTy(gdctx.ty)
Kunshan Wang's avatar
Kunshan Wang committed
352
        val gc = mkGlobalCell(ty)
Kunshan Wang's avatar
Kunshan Wang committed
353
        gc.id = idFactory.getID()
Kunshan Wang's avatar
Kunshan Wang committed
354
        gc.name = Some(gdctx.nam)
Kunshan Wang's avatar
Kunshan Wang committed
355
        addGlobalCell(gc)
Kunshan Wang's avatar
Kunshan Wang committed
356
357
      }
      case fdecl: FuncDeclContext => {
Kunshan Wang's avatar
Kunshan Wang committed
358
359
360
361
362
363
        val name = tokenToString(fdecl.nam)
        findOldFunc(name) match {
          case Some(oldFunc) =>
            throw new TextIRParsingException(inCtx(fdecl, "Function %s already declared in previous bundles. Old func: %s".format(name, oldFunc.repr)))
          case None => declFunc(name, fdecl.funcSig)
        }
Kunshan Wang's avatar
Kunshan Wang committed
364
365
      }
      case fdef: FuncDefContext => {
Kunshan Wang's avatar
Kunshan Wang committed
366
        val func = findOldFunc(fdef.nam).getOrElse(declFunc(fdef.nam, fdef.funcSig))
Kunshan Wang's avatar
Kunshan Wang committed
367
        //bundle.defFuncNs.add(func)
Kunshan Wang's avatar
Kunshan Wang committed
368
        funcDefs += ((func, fdef))
Kunshan Wang's avatar
Kunshan Wang committed
369
      }
Kunshan Wang's avatar
Kunshan Wang committed
370
      case edef: FuncExpDefContext => {
371
372
373
374
375
        val efun = mkExpo(edef)
        efun.id = idFactory.getID()
        efun.name = Some(edef.nam)
        addExpFunc(efun)
      }
Kunshan Wang's avatar
Kunshan Wang committed
376
377
378
379
380
      case _ => {}
    }

    phase2.doAll()

Kunshan Wang's avatar
Kunshan Wang committed
381
    def defFunc(func: Function, fDefCtx: FuncDefContext) {
Kunshan Wang's avatar
Kunshan Wang committed
382
      val ver = new FuncVer()
Kunshan Wang's avatar
Kunshan Wang committed
383
      val verName = globalize(fDefCtx.ver, func.name.get)
Kunshan Wang's avatar
Kunshan Wang committed
384
      ver.id = idFactory.getID()
Kunshan Wang's avatar
Kunshan Wang committed
385
      ver.name = Some(verName)
Kunshan Wang's avatar
Kunshan Wang committed
386
387
      addFuncVer(ver)

Kunshan Wang's avatar
Kunshan Wang committed
388
      ver.func = func
Kunshan Wang's avatar
Kunshan Wang committed
389
      //func.versions = ver :: func.versions  // Don't override here. Let the MicroVM redefine functions.
Kunshan Wang's avatar
Kunshan Wang committed
390

Kunshan Wang's avatar
Kunshan Wang committed
391
      def globalizeBB(name: String): String = globalize(name, verName)
Kunshan Wang's avatar
Kunshan Wang committed
392

Kunshan Wang's avatar
Kunshan Wang committed
393
394
395
396
397
398
399
400
401

      // Resolve function version local entities

      implicit def resBB(ctx: BbContext): BasicBlock = catchIn(ctx, "Unable to resolve basic block") {
        resBBByName(ctx.name.getText)
      }
      def resBBByName(name: String): BasicBlock = {
        val globalName = globalize(name, verName)
        ver.bbNs(globalName)
Kunshan Wang's avatar
Kunshan Wang committed
402
403
      }

Kunshan Wang's avatar
Kunshan Wang committed
404
      val phase4 = new Later() // Resolve references from instructions to other variables (global or local) and basic blocks
Kunshan Wang's avatar
Kunshan Wang committed
405

Kunshan Wang's avatar
Kunshan Wang committed
406
      def makeBB(bbCtx: BasicBlockContext): BasicBlock = {
Kunshan Wang's avatar
Kunshan Wang committed
407
408
        val label = bbCtx.label()
        val bbName = globalize(label.name(), verName)
Kunshan Wang's avatar
Kunshan Wang committed
409
        val bb = new BasicBlock()
Kunshan Wang's avatar
Kunshan Wang committed
410
        bb.id = idFactory.getID()
Kunshan Wang's avatar
Kunshan Wang committed
411
        bb.name = Some(bbName)
Kunshan Wang's avatar
Kunshan Wang committed
412
        ver.bbNs.add(bb)
Kunshan Wang's avatar
Kunshan Wang committed
413

Kunshan Wang's avatar
Kunshan Wang committed
414
415
416
417
418
419
        def mkNorParam(ty: Type, name: String): NorParam = {
          val param = NorParam(ty)
          param.id = idFactory.getID()
          param.name = Some(globalize(name, bbName))
          param
        }
Kunshan Wang's avatar
Kunshan Wang committed
420

Kunshan Wang's avatar
Kunshan Wang committed
421
422
423
424
425
426
        def mkExcParam(name: String): ExcParam = {
          val param = ExcParam()
          param.id = idFactory.getID()
          param.name = Some(globalize(name, bbName))
          param
        }
Kunshan Wang's avatar
Kunshan Wang committed
427

Kunshan Wang's avatar
Kunshan Wang committed
428
429
        bb.norParams = label.bbParam.map(p => mkNorParam(p.`type`(), p.name()))
        bb.excParam = Option(label.excParam).map(p => mkExcParam(p.name()))
Kunshan Wang's avatar
Kunshan Wang committed
430

Kunshan Wang's avatar
Kunshan Wang committed
431
432
        bb.norParams.foreach(bb.localVarNs.add)
        bb.excParam.foreach(bb.localVarNs.add)
Kunshan Wang's avatar
Kunshan Wang committed
433

Kunshan Wang's avatar
Kunshan Wang committed
434
        // Resolve basic block local entities (variables)
Kunshan Wang's avatar
Kunshan Wang committed
435

Kunshan Wang's avatar
Kunshan Wang committed
436
437
438
439
440
441
442
        def resLocalVar(ctx: ValueContext): LocalVariable = catchIn(ctx, "Unable to resolve local variable") {
          resLocalVarByName(ctx.name)
        }
        def resLocalVarByName(name: String): LocalVariable = {
          val globalName = globalize(name, bbName)
          bb.localVarNs(globalName)
        }
Kunshan Wang's avatar
Kunshan Wang committed
443

Kunshan Wang's avatar
Kunshan Wang committed
444
445
446
447
448
449
450
451
452
        implicit def resVar(ctx: ValueContext): SSAVariable = catchIn(ctx, "Unable to resolve variable") {
          resVarByName(ctx.name)
        }
        def resVarByName(name: String): SSAVariable = {
          val globalName = globalize(name, bbName)
          bb.localVarNs.get(globalName).getOrElse {
            cascadeLookup(globalName, bundle.globalVarNs, globalBundle.globalVarNs)
          }
        }
Kunshan Wang's avatar
Kunshan Wang committed
453

Kunshan Wang's avatar
Kunshan Wang committed
454
        implicit def resArgList(a: ArgListContext): Seq[SSAVariable] = a.value.map(resVar)
Kunshan Wang's avatar
Kunshan Wang committed
455

Kunshan Wang's avatar
Kunshan Wang committed
456
        implicit def resKA(ka: KeepAliveClauseContext): Seq[LocalVariable] = ka.value.map(resLocalVar)
Kunshan Wang's avatar
Kunshan Wang committed
457

Kunshan Wang's avatar
Kunshan Wang committed
458
459
        def resFuncCallBody(fcb: FuncCallBodyContext): (FuncSig, SSAVariable, Seq[SSAVariable]) =
          (fcb.funcSig, fcb.callee, fcb.argList)
Kunshan Wang's avatar
Kunshan Wang committed
460

Kunshan Wang's avatar
Kunshan Wang committed
461
462
463
464
465
466
467
        def asgnFuncCallBody(cl: CallLike, fcb: FuncCallBodyContext): Unit = {
          val (sig, callee, argList) = resFuncCallBody(fcb)
          cl.sig = sig; cl.callee = callee; cl.argList = argList
        }
        
        implicit def resDestClause(dc: DestClauseContext): DestClause = {
          DestClause(dc.bb, dc.argList())
Kunshan Wang's avatar
Kunshan Wang committed
468
469
        }

Kunshan Wang's avatar
Kunshan Wang committed
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
        implicit def resExcClause(ec: ExcClauseContext): Option[ExcClause] =
          if (ec.nor == null) {
            None
          } else {
            Some(ExcClause(ec.nor, ec.exc))
          }
        
        // Make instruction

        def mkInst(bb: BasicBlock, instDef: InstContext): Instruction = {

          val inst: Instruction = instDef.instBody match {
            case ii: InstBinOpContext =>
              InstBinOp(BinOptr.withName(ii.binop.getText), ii.`type`, null, null, null).later(phase4) { i =>
                i.op1 = ii.op1; i.op2 = ii.op2; i.excClause = ii.excClause
              }
            case ii: InstCmpContext =>
              InstCmp(CmpOptr.withName(ii.cmpop.getText), ii.`type`, null, null).later(phase4) { i =>
                i.op1 = ii.op1; i.op2 = ii.op2
              }
            case ii: InstConversionContext =>
              InstConv(ConvOptr.withName(ii.convop.getText), ii.fromTy, ii.toTy, null).later(phase4) { i =>
                i.opnd = ii.opnd
              }
            case ii: InstSelectContext =>
              InstSelect(ii.condTy, ii.resTy, null, null, null).later(phase4) { i =>
                i.cond = ii.cond; i.ifTrue = ii.ifTrue; i.ifFalse = ii.ifFalse
              }
            case ii: InstBranchContext =>
              InstBranch(null).later(phase4) { i =>
                i.dest = ii.dest
              }
            case ii: InstBranch2Context =>
              InstBranch2(null, null, null).later(phase4) { i =>
                i.cond = ii.cond; i.ifTrue = ii.ifTrue; i.ifFalse = ii.ifFalse
              }
            case ii: InstSwitchContext =>
              InstSwitch(ii.`type`, null, null, null).later(phase4) { i =>
                i.opnd = ii.opnd; i.defDest = ii.defDest
                i.cases = for ((v, d) <- ii.caseVal.zip(ii.caseDest)) yield (resVar(v), resDestClause(d))
              }
            case ii: InstCallContext =>
              InstCall(null, null, null, null, null).later(phase4) { i =>
                asgnFuncCallBody(i, ii.funcCallBody)
                i.excClause = ii.excClause; i.keepAlives = ii.keepAliveClause
              }
            case ii: InstTailCallContext =>
              InstTailCall(null, null, null).later(phase4) { i =>
                asgnFuncCallBody(i, ii.funcCallBody)
              }
            case ii: InstRetContext =>
              InstRet(ver, null).later(phase4) { i =>
                i.retVal = ii.retVal
              }
            case ii: InstThrowContext =>
              InstThrow(null).later(phase4) { i =>
                i.excVal = ii.exc
              }
            case ii: InstExtractValueContext =>
              InstExtractValue(needStruct(ii.`type`), ii.intLiteral.intValue, null).later(phase4) { i =>
                i.opnd = ii.opnd
              }
            case ii: InstInsertValueContext =>
              InstInsertValue(needStruct(ii.`type`), ii.intLiteral.intValue, null, null).later(phase4) { i =>
                i.opnd = ii.opnd; i.newVal = ii.newVal
              }
            case ii: InstExtractElementContext =>
              InstExtractElement(needSeq(ii.seqTy), needInt(ii.indTy), null, null).later(phase4) { i =>
                i.opnd = ii.opnd; i.index = ii.index
              }
            case ii: InstInsertElementContext =>
              InstInsertElement(needSeq(ii.seqTy), needInt(ii.indTy), null, null, null).later(phase4) { i =>
                i.opnd = ii.opnd; i.index = ii.index; i.newVal = ii.newVal
              }
            case ii: InstShuffleVectorContext =>
              InstShuffleVector(needVector(ii.vecTy), needVector(ii.maskTy), null, null, null).later(phase4) { i =>
                i.vec1 = ii.vec1; i.vec2 = ii.vec2; i.mask = ii.mask
              }
            case ii: InstNewContext =>
              InstNew(ii.allocTy, null).later(phase4) { i =>
                i.excClause = ii.excClause
              }
            case ii: InstNewHybridContext =>
              InstNewHybrid(needHybrid(ii.allocTy), needInt(ii.lenTy), null, null).later(phase4) { i =>
                i.length = ii.length; i.excClause = ii.excClause
              }
            case ii: InstAllocaContext =>
              InstAlloca(ii.allocTy, null).later(phase4) { i =>
                i.excClause = ii.excClause
              }
            case ii: InstAllocaHybridContext =>
              InstAllocaHybrid(needHybrid(ii.allocTy), needInt(ii.lenTy), null, null).later(phase4) { i =>
                i.length = ii.length; i.excClause = ii.excClause
              }
            case ii: InstGetIRefContext =>
              InstGetIRef(ii.refTy, null).later(phase4) { i =>
                i.opnd = ii.opnd
              }
            case ii: InstGetFieldIRefContext =>
              InstGetFieldIRef(ii.ptr != null, needStruct(ii.refTy), ii.intLiteral.intValue, null).later(phase4) { i =>
                i.opnd = ii.opnd
              }
            case ii: InstGetElemIRefContext =>
              InstGetElemIRef(ii.ptr != null, needSeq(ii.refTy), needInt(ii.indTy), null, null).later(phase4) { i =>
                i.opnd = ii.opnd; i.index = ii.index
              }
            case ii: InstShiftIRefContext =>
              InstShiftIRef(ii.ptr != null, ii.refTy, needInt(ii.offTy), null, null).later(phase4) { i =>
                i.opnd = ii.opnd; i.offset = ii.offset
              }
            case ii: InstGetFixedPartIRefContext =>
              InstGetFixedPartIRef(ii.ptr != null, needHybrid(ii.refTy), null).later(phase4) { i =>
                i.opnd = ii.opnd
              }
            case ii: InstGetVarPartIRefContext =>
              InstGetVarPartIRef(ii.ptr != null, needHybrid(ii.refTy), null).later(phase4) { i =>
                i.opnd = ii.opnd
              }
            case ii: InstLoadContext =>
              InstLoad(ii.ptr != null, ii.memord, ii.`type`, null, null).later(phase4) { i =>
                i.loc = ii.loc
                i.excClause = ii.excClause
              }
            case ii: InstStoreContext =>
              InstStore(ii.ptr != null, ii.memord, ii.`type`, null, null, null).later(phase4) { i =>
                i.loc = ii.loc; i.newVal = ii.newVal
                i.excClause = ii.excClause
              }
            case ii: InstCmpXchgContext =>
              InstCmpXchg(ii.ptr != null, ii.isWeak != null, ii.ordSucc, ii.ordFail, ii.`type`, null, null, null, null).later(phase4) { i =>
                i.loc = ii.loc; i.expected = ii.expected; i.desired = ii.desired
                i.excClause = ii.excClause
              }
            case ii: InstAtomicRMWContext =>
              InstAtomicRMW(ii.ptr != null, ii.memord, AtomicRMWOptr.withName(ii.atomicrmwop.getText), ii.`type`, null, null, null).later(phase4) { i =>
                i.loc = ii.loc; i.opnd = ii.opnd
                i.excClause = ii.excClause
              }
            case ii: InstFenceContext =>
              InstFence(ii.memord)
            case ii: InstTrapContext =>
              InstTrap(ii.`type`, null, null).later(phase4) { i =>
                i.excClause = ii.excClause; i.keepAlives = ii.keepAliveClause
              }
            case ii: InstWatchPointContext =>
              InstWatchPoint(ii.intLiteral.intValue(), ii.`type`, null, null, null, null).later(phase4) { i =>
                i.dis = ii.dis; i.ena = ii.ena; i.exc = Option(ii.wpExc).map(resDestClause); i.keepAlives = ii.keepAliveClause
              }
            case ii: InstCCallContext =>
              InstCCall(ii.callConv, ii.funcTy, ii.funcSig, null, null, null).later(phase4) { i =>
                i.callee = ii.callee; i.argList = ii.argList; i.keepAlives = ii.keepAliveClause
              }
            case ii: InstNewStackContext =>
              InstNewStack(null, null, null, null).later(phase4) { i =>
                asgnFuncCallBody(i, ii.funcCallBody)
                i.excClause = ii.excClause
              }
            case ii: InstSwapStackContext =>
              InstSwapStack(null, null, null, null, null).later(phase4) { i =>
                i.swappee = ii.swappee;
                i.curStackAction = ii.curStackClause match {
                  case a: CurStackRetWithContext => RetWith(a.`type`)
                  case a: CurStackKillOldContext => KillOld()
                }
                i.newStackAction = ii.newStackClause match {
                  case a: NewStackPassValueContext => PassValue(a.`type`, a.value)
                  case a: NewStackThrowExcContext  => ThrowExc(a.exc)
                }
                i.excClause = ii.excClause; i.keepAlives = ii.keepAliveClause
              }
            case ii: InstCommInstContext =>
              InstCommInst(CommInsts(ii.nam), Option(ii.flagList()).map(convFlagList).getOrElse(Seq()), null, null, null, null, null).later(phase4) { i =>
                i.typeList = Option(ii.typeList).map(resTypeList).getOrElse(Seq())
                i.funcSigList = Option(ii.funcSigList).map(resFuncSigList).getOrElse(Seq())
                i.argList = Option(ii.argList).map(resArgList).getOrElse(Seq())
                i.excClause = ii.excClause; i.keepAlives = ii.keepAliveClause
              }
          }
Kunshan Wang's avatar
Kunshan Wang committed
648

Kunshan Wang's avatar
Kunshan Wang committed
649
650
          inst.id = idFactory.getID()
          inst.name = Option(instDef.name).map(n => globalize(n.getText, bbName))
Kunshan Wang's avatar
Kunshan Wang committed
651

Kunshan Wang's avatar
Kunshan Wang committed
652
          bb.localVarNs.add(inst)
Kunshan Wang's avatar
Kunshan Wang committed
653

Kunshan Wang's avatar
Kunshan Wang committed
654
          return inst
Kunshan Wang's avatar
Kunshan Wang committed
655
656
        }

Kunshan Wang's avatar
Kunshan Wang committed
657
        bb.insts = bbCtx.inst.map(i => mkInst(bb, i))
658

Kunshan Wang's avatar
Kunshan Wang committed
659
        return bb
Kunshan Wang's avatar
Kunshan Wang committed
660
661
      }

Kunshan Wang's avatar
Kunshan Wang committed
662
      val bbs = fDefCtx.funcBody.basicBlock().map(makeBB)
Kunshan Wang's avatar
Kunshan Wang committed
663

Kunshan Wang's avatar
Kunshan Wang committed
664
      ver.bbs = bbs
Kunshan Wang's avatar
Kunshan Wang committed
665
      ver.entry = bbs.head
Kunshan Wang's avatar
Kunshan Wang committed
666
667
668
669

      phase4.doAll()
    }

Kunshan Wang's avatar
Kunshan Wang committed
670
671
    for ((func, fDefCtx) <- funcDefs) {
      defFunc(func, fDefCtx)
Kunshan Wang's avatar
Kunshan Wang committed
672
673
    }

Kunshan Wang's avatar
Kunshan Wang committed
674
675
    return bundle
  }
Kunshan Wang's avatar
Kunshan Wang committed
676
677
678
}

object UIRTextReader {
Kunshan Wang's avatar
Kunshan Wang committed
679
  def globalize(name: String, parentName: String): String = {
Kunshan Wang's avatar
Kunshan Wang committed
680
681
    val sigil = name.charAt(0)
    sigil match {
682
      case '@' => name
Kunshan Wang's avatar
Kunshan Wang committed
683
      case '%' => parentName + "." + name.substring(1)
684
      case _   => throw new UvmException("Illegal name '%s'. Name must begin with either '@' or '%%'".format(name))
Kunshan Wang's avatar
Kunshan Wang committed
685
686
    }
  }
Kunshan Wang's avatar
Kunshan Wang committed
687
}