InstructionExecutor.scala 20.9 KB
Newer Older
Kunshan Wang's avatar
Kunshan Wang committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
package uvm.refimpl.itpr

import scala.annotation.tailrec
import scala.collection.mutable.ArrayBuffer
import org.slf4j.LoggerFactory
import com.typesafe.scalalogging.Logger
import uvm._
import uvm.comminsts._
import uvm.refimpl._
import uvm.refimpl.mem._
import uvm.refimpl.mem.TypeSizes.Word
import uvm.ssavariables._
import uvm.types._
import uvm.refimpl.nat.NativeCallResult

/**
 * Part of the InterpreterThread. It isolates the GIANT case-matching function.
 */
Kunshan Wang's avatar
Kunshan Wang committed
19
trait InstructionExecutor extends InterpreterActions with CommInstExecutor {
Kunshan Wang's avatar
Kunshan Wang committed
20 21
  import InterpreterThread.logger

Kunshan Wang's avatar
Kunshan Wang committed
22 23 24
  protected def mutator: Mutator
  implicit protected def microVM: MicroVM
  implicit protected def memorySupport: MemorySupport
Kunshan Wang's avatar
Kunshan Wang committed
25 26

  /** Interpret the current instruction. */
Kunshan Wang's avatar
Kunshan Wang committed
27
  protected def interpretCurrentInstruction(): Unit = try {
Kunshan Wang's avatar
Kunshan Wang committed
28 29 30 31 32 33
    logger.debug(ctx + "Executing instruction...")

    curInst match {
      case i @ InstBinOp(op, opndTy, op1, op2, excClause) => {
        def doScalar(scalarTy: Type, b1: ValueBox, b2: ValueBox, br: ValueBox): Unit = {
          scalarTy match {
34 35 36 37
            case TypeInt(l)   => br.asIntRaw = PrimOpHelpers.intBinOp(op, l, b1.asIntRaw, b2.asIntRaw, ctx)
            case TypeFloat()  => br.asFloat = PrimOpHelpers.floatBinOp(op, b1.asFloat, b2.asFloat, ctx)
            case TypeDouble() => br.asDouble = PrimOpHelpers.doubleBinOp(op, b1.asDouble, b2.asDouble, ctx)
            case _            => throw new UvmRuntimeException(ctx + "BinOp not suitable for type %s".format(scalarTy))
Kunshan Wang's avatar
Kunshan Wang committed
38 39 40 41 42 43
          }
        }

        try {
          opndTy match {
            case TypeVector(scalarTy, sz) => {
44
              for (((b1, b2), br) <- ((op1.asSeq zip op2.asSeq) zip results(0).asSeq)) {
Kunshan Wang's avatar
Kunshan Wang committed
45 46 47
                doScalar(scalarTy, b1, b2, br)
              }
            }
48
            case scalarTy => doScalar(scalarTy, op1, op2, results(0))
Kunshan Wang's avatar
Kunshan Wang committed
49 50 51 52 53 54 55 56 57 58 59 60 61 62
          }
          continueNormally()
        } catch {
          case e: UvmDivisionByZeroException => excClause match {
            case None => throw e
            case Some(ec) => {
              branchTo(ec.exc)
            }
          }
        }
      }

      case i @ InstCmp(op, opndTy, op1, op2) => {
        def doScalar(scalarTy: Type, b1: ValueBox, b2: ValueBox, br: ValueBox): Unit = {
63 64 65 66 67 68 69 70 71 72 73 74 75
          br.asBoolean = scalarTy match {
            case TypeInt(l)      => PrimOpHelpers.intCmp(op, l, b1.asIntRaw, b2.asIntRaw, ctx)
            case TypeFloat()     => PrimOpHelpers.floatCmp(op, b1.asFloat, b2.asFloat, ctx)
            case TypeDouble()    => PrimOpHelpers.doubleCmp(op, b1.asDouble, b2.asDouble, ctx)
            case TypeRef(_)      => PrimOpHelpers.refCmp(op, b1.asRef, b2.asRef, ctx)
            case TypeFuncRef(_)  => PrimOpHelpers.objCmp(op, b1.asFunc, b2.asFunc, "funcref", ctx)
            case TypeStackRef()  => PrimOpHelpers.objCmp(op, b1.asStack, b2.asStack, "stackref", ctx)
            case TypeThreadRef() => PrimOpHelpers.objCmp(op, b1.asThread, b2.asThread, "threadref", ctx)
            case TypeIRef(_) => {
              val (op1b, op1o) = b1.asIRef
              val (op2b, op2o) = b2.asIRef
              PrimOpHelpers.irefCmp(op, op1b, op1o, op2b, op2o, ctx)
            }
76
            case t:AbstractPointerType  => PrimOpHelpers.intCmp(op, TypeSizes.WORD_SIZE_BITS.toInt, b1.asPtr, b2.asPtr, ctx)
77
            case _ => throw new UvmRuntimeException(ctx + "Comparison not suitable for type %s".format(opndTy))
Kunshan Wang's avatar
Kunshan Wang committed
78 79 80 81 82
          }
        }

        opndTy match {
          case TypeVector(scalarTy, sz) => {
83
            for (((b1, b2), br) <- ((op1.asSeq zip op2.asSeq) zip results(0).asSeq)) {
Kunshan Wang's avatar
Kunshan Wang committed
84 85 86
              doScalar(scalarTy, b1, b2, br)
            }
          }
87
          case scalarTy => doScalar(scalarTy, op1, op2, results(0))
Kunshan Wang's avatar
Kunshan Wang committed
88 89 90 91 92 93 94 95 96
        }

        continueNormally()
      }

      case i @ InstConv(op, fromTy, toTy, opnd) => {
        def doScalar(scalarFromTy: Type, scalarToTy: Type, bOpnd: ValueBox, br: ValueBox): Unit = {
          def iToI(): Unit = (scalarFromTy, scalarToTy) match {
            case (TypeInt(fl), TypeInt(tl)) => {
97
              val od = bOpnd.asIntRaw
Kunshan Wang's avatar
Kunshan Wang committed
98 99 100 101 102
              val result = op match {
                case ConvOptr.TRUNC => OpHelper.trunc(od, tl)
                case ConvOptr.ZEXT  => OpHelper.zext(od, fl, tl)
                case ConvOptr.SEXT  => OpHelper.sext(od, fl, tl)
              }
103
              br.asIntRaw = result
Kunshan Wang's avatar
Kunshan Wang committed
104 105 106 107 108 109 110 111 112 113
            }
            case _ => throw new UvmRuntimeException(ctx + "Expect integer source and dest type. Found %s and %s".format(scalarFromTy, scalarToTy))
          }

          def fpToI(signed: Boolean): Unit = {
            val tl = scalarToTy match {
              case TypeInt(l) => l
              case _          => throw new UvmRuntimeException(ctx + "Expect integer dest type. Found %s".format(scalarToTy))
            }
            val result = scalarFromTy match {
114 115
              case TypeFloat()  => OpHelper.floatToI(bOpnd.asFloat, tl, signed)
              case TypeDouble() => OpHelper.doubleToI(bOpnd.asDouble, tl, signed)
Kunshan Wang's avatar
Kunshan Wang committed
116 117
              case _            => throw new UvmRuntimeException(ctx + "Expect FP source type. Found %s.".format(scalarFromTy))
            }
118
            br.asIntRaw = result
Kunshan Wang's avatar
Kunshan Wang committed
119 120 121 122 123 124 125
          }

          def iToFP(signed: Boolean): Unit = {
            val fl = scalarFromTy match {
              case TypeInt(l) => l
              case _          => throw new UvmRuntimeException(ctx + "Expect integer source type. Found %s".format(scalarFromTy))
            }
126
            val od = bOpnd.asIntRaw
Kunshan Wang's avatar
Kunshan Wang committed
127 128
            val extended = if (signed) OpHelper.prepareSigned(od, fl) else OpHelper.prepareUnsigned(od, fl)
            scalarToTy match {
129 130 131
              case TypeFloat()  => br.asFloat = extended.toFloat
              case TypeDouble() => br.asDouble = extended.toDouble
              case _            => throw new UvmRuntimeException(ctx + "Expect FP dest type. Found %s.".format(scalarToTy))
Kunshan Wang's avatar
Kunshan Wang committed
132 133 134 135
            }
          }

          def bitcast(): Unit = (scalarFromTy, scalarToTy) match {
136 137 138 139
            case (TypeInt(32), TypeFloat())  => br.asFloat = java.lang.Float.intBitsToFloat(bOpnd.asIntRaw.intValue)
            case (TypeInt(64), TypeDouble()) => br.asDouble = java.lang.Double.longBitsToDouble(bOpnd.asIntRaw.longValue)
            case (TypeFloat(), TypeInt(32))  => br.asInt32 = java.lang.Float.floatToRawIntBits(bOpnd.asFloat)
            case (TypeDouble(), TypeInt(64)) => br.asInt64 = java.lang.Double.doubleToRawLongBits(bOpnd.asDouble)
Kunshan Wang's avatar
Kunshan Wang committed
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
            case _ => throw new UvmRuntimeException(ctx +
              "BITCAST can only convert between int and FP types of the same size. Found %s and %s.".format(scalarFromTy, scalarToTy))
          }

          def refcast(): Unit = (scalarFromTy, scalarToTy) match {
            case (TypeRef(_), TypeRef(_))         => br.copyFrom(bOpnd)
            case (TypeIRef(_), TypeIRef(_))       => br.copyFrom(bOpnd)
            case (TypeFuncRef(_), TypeFuncRef(_)) => br.copyFrom(bOpnd)
            case _ => throw new UvmRuntimeException(ctx +
              "REFCAST can only convert between two types both of which are ref, iref, or func. Found %s and %s.".format(scalarFromTy, scalarToTy))
          }

          def ptrcast(): Unit = {
            (scalarFromTy, scalarToTy) match {
              case (TypeInt(_), TypeInt(_)) => throw new UvmRuntimeException(ctx +
                "PTRCAST cannot convert between two int types. Found %s and %s.".format(scalarFromTy, scalarToTy))
              case _ =>
            }
            val srcAddr: Word = scalarFromTy match {
159 160
              case TypeInt(n)             => bOpnd.getUInt(n).longValue // truncates
              case _: AbstractPointerType => bOpnd.asPtr
Kunshan Wang's avatar
Kunshan Wang committed
161 162
            }
            scalarToTy match {
163 164
              case TypeInt(n)             => br.setInt(srcAddr, Math.min(n, 64))
              case _: AbstractPointerType => br.asPtr = srcAddr
Kunshan Wang's avatar
Kunshan Wang committed
165 166 167 168
            }
          }

          op match {
169 170 171 172 173
            case ConvOptr.TRUNC   => iToI()
            case ConvOptr.ZEXT    => iToI()
            case ConvOptr.SEXT    => iToI()
            case ConvOptr.FPTRUNC => br.asFloat = bOpnd.asDouble.toFloat
            case ConvOptr.FPEXT   => br.asDouble = bOpnd.asFloat.toDouble
Kunshan Wang's avatar
Kunshan Wang committed
174 175 176 177 178 179 180 181 182 183 184 185 186 187
            case ConvOptr.FPTOUI  => fpToI(signed = false)
            case ConvOptr.FPTOSI  => fpToI(signed = true)
            case ConvOptr.UITOFP  => iToFP(signed = false)
            case ConvOptr.SITOFP  => iToFP(signed = true)
            case ConvOptr.BITCAST => bitcast()
            case ConvOptr.REFCAST => refcast()
            case ConvOptr.PTRCAST => ptrcast()
          }
        }

        (fromTy, toTy) match {
          case (TypeVector(scalarFromTy, sz), TypeVector(scalarToTy, sz2)) => {
            if (sz != sz2) throw new UvmRefImplException(ctx + "The source and dest vector types must have the same length")

188
            for ((bOpnd, br) <- (opnd.asSeq zip results(0).asSeq)) {
Kunshan Wang's avatar
Kunshan Wang committed
189 190 191
              doScalar(scalarFromTy, scalarToTy, bOpnd, br)
            }
          }
192
          case _ => doScalar(fromTy, toTy, opnd, results(0))
Kunshan Wang's avatar
Kunshan Wang committed
193 194 195 196 197 198 199
        }

        incPC()
      }

      case i @ InstSelect(condTy, opndTy, cond, ifTrue, ifFalse) => {
        def doScalar(bCond: ValueBox, bTrue: ValueBox, bFalse: ValueBox, br: ValueBox): Unit = {
200
          if (bCond.asBoolean) {
Kunshan Wang's avatar
Kunshan Wang committed
201 202 203 204 205 206 207 208
            br.copyFrom(bTrue)
          } else {
            br.copyFrom(bFalse)
          }
        }

        condTy match {
          case TypeVector(TypeInt(1), sz) => {
209
            for ((((bCond, bTrue), bFalse), br) <- (cond.asSeq zip ifTrue.asSeq zip ifFalse.asSeq zip results(0).asSeq)) {
Kunshan Wang's avatar
Kunshan Wang committed
210 211 212 213
              doScalar(bCond, bTrue, bFalse, br)
            }
          }
          case TypeInt(1) => {
214
            doScalar(cond, ifTrue, ifFalse, results(0))
Kunshan Wang's avatar
Kunshan Wang committed
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
          }
          case _ => throw new UvmRefImplException(ctx + "Condition must be either int<1> or a vector of int<1>. Found %s".format(condTy))
        }

        continueNormally()
      }

      case i @ InstBranch(dest) => {
        branchTo(dest)
      }

      case i @ InstBranch2(cond, ifTrue, ifFalse) => {
        val cv = boxOf(cond).asInstanceOf[BoxInt].value
        val dest = if (cv == 1) ifTrue else ifFalse
        branchTo(dest)
      }

      case i @ InstSwitch(opndTy, opnd, defDest, cases) => {
        opndTy match {
          case TypeInt(l) => {
            val ov = boxOf(opnd).asInstanceOf[BoxInt].value
            val dest = cases.find(pair => boxOf(pair._1).asInstanceOf[BoxInt].value == ov).map(_._2).getOrElse(defDest)
            branchTo(dest)
          }
          case _ => throw new UvmRefImplException(ctx + "Operand type must be integer. %s found.".format(opndTy))
        }
      }

      case i @ InstCall(sig, callee, argList, excClause, keepAlives) => {
244
        val calleeFunc = callee.asFunc.getOrElse {
Kunshan Wang's avatar
Kunshan Wang committed
245 246 247 248 249 250 251
          throw new UvmRuntimeException(ctx + "Callee must not be NULL")
        }

        val argBoxes = argList.map(boxOf)

        val shouldIncrementPC = curStack.callMu(calleeFunc, argBoxes)
        if (shouldIncrementPC) {
252
          throw new UvmRefImplException(ctx + "Should not continue normally immediately after calling")
Kunshan Wang's avatar
Kunshan Wang committed
253 254 255 256
        }
      }

      case i @ InstTailCall(sig, callee, argList) => {
257
        val calleeFunc = callee.asFunc.getOrElse {
Kunshan Wang's avatar
Kunshan Wang committed
258 259 260 261 262 263 264
          throw new UvmRuntimeException(ctx + "Callee must not be NULL")
        }

        val argBoxes = argList.map(boxOf)

        val shouldIncrementPC = curStack.tailCallMu(calleeFunc, argBoxes)
        if (shouldIncrementPC) {
265
          throw new UvmRefImplException(ctx + "Should not continue normally immediately after tail-calling")
Kunshan Wang's avatar
Kunshan Wang committed
266 267 268 269 270 271 272 273 274 275 276 277
        }
      }

      case i @ InstRet(funcVer, retVals) => {
        val rvbs = retVals.map(boxOf)
        val shouldIncrementPC = curStack.retFromMu(rvbs)
        if (shouldIncrementPC) {
          continueNormally()
        }
      }

      case i @ InstThrow(excVal) => {
278
        val exc = excVal.asRef
279
        curStack.popMuFrameForThrow()
Kunshan Wang's avatar
Kunshan Wang committed
280 281 282 283
        catchException(exc)
      }

      case i @ InstExtractValue(strTy, index, opnd) => {
284
        results(0) copyFrom opnd.asSeq(index)
Kunshan Wang's avatar
Kunshan Wang committed
285 286 287 288 289
        continueNormally()
      }

      case i @ InstInsertValue(strTy, index, opnd, newVal) => {
        val nvb = boxOf(newVal)
290
        for (((ofb, ifb), ind) <- (opnd.asSeq zip results(0).asSeq).zipWithIndex) {
Kunshan Wang's avatar
Kunshan Wang committed
291 292 293 294 295 296 297 298 299 300
          if (ind == index) {
            ifb.copyFrom(nvb)
          } else {
            ifb.copyFrom(ofb)
          }
        }
        continueNormally()
      }

      case i @ InstExtractElement(vecTy, indTy, opnd, index) => {
301
        val ind = index.getUInt(indTy.length).toLong
Kunshan Wang's avatar
Kunshan Wang committed
302 303 304 305 306

        if (ind > vecTy.len) {
          throw new UvmRuntimeException(ctx + "Index %d out of range. Vector type: %s".format(ind, vecTy))
        }

307
        results(0) copyFrom opnd.asSeq(ind.toInt)
Kunshan Wang's avatar
Kunshan Wang committed
308 309 310 311
        continueNormally()
      }

      case i @ InstInsertElement(vecTy, indTy, opnd, index, newVal) => {
312
        val ind = index.getUInt(indTy.length).toLong
Kunshan Wang's avatar
Kunshan Wang committed
313 314 315 316 317 318 319 320

        if (ind > vecTy.len) {
          throw new UvmRuntimeException(ctx + "Index %d out of range. Vector type: %s".format(ind, vecTy))
        }

        val indInt = ind.intValue
        val nvb = boxOf(newVal)

321
        for (((oeb, ieb), ind2) <- (opnd.asSeq zip results(0).asSeq).zipWithIndex) {
Kunshan Wang's avatar
Kunshan Wang committed
322 323 324 325 326 327 328 329 330 331 332 333
          if (ind2 == indInt) {
            ieb.copyFrom(nvb)
          } else {
            ieb.copyFrom(oeb)
          }
        }
        continueNormally()
      }

      case i @ InstShuffleVector(vecTy, maskTy, vec1, vec2, mask) => {
        val vecLen = vecTy.len.toInt
        val maskIntLen = maskTy.elemTy.asInstanceOf[TypeInt].length
334 335 336 337
        val v1s = vec1.asSeq
        val v2s = vec2.asSeq
        val ms = mask.asSeq
        val is = results(0).asSeq
Kunshan Wang's avatar
Kunshan Wang committed
338

339 340
        for (((meb, ieb), ind) <- (ms zip is).zipWithIndex) {
          val me = meb.getUInt(maskIntLen).toInt
Kunshan Wang's avatar
Kunshan Wang committed
341
          if (me < vecLen) {
342
            ieb.copyFrom(v1s(me))
Kunshan Wang's avatar
Kunshan Wang committed
343
          } else if (vecLen <= me && me < vecLen * 2) {
344
            ieb.copyFrom(v2s(me - vecLen))
Kunshan Wang's avatar
Kunshan Wang committed
345 346 347 348 349 350 351 352 353 354
          } else {
            throw new UvmRuntimeException(ctx + "Index %d as the %d-th element of mask is out of range. Vector type: %s".format(me, ind, vecTy))
          }
        }
        continueNormally()
      }

      case i @ InstNew(allocTy, excClause) => {
        handleOutOfMemory(excClause) {
          val addr = mutator.newScalar(allocTy)
355
          results(0).asRef = addr
Kunshan Wang's avatar
Kunshan Wang committed
356 357 358 359 360 361
          continueNormally()
        }
      }

      case i @ InstNewHybrid(allocTy, lenTy, length, excClause) => {
        handleOutOfMemory(excClause) {
362 363 364
          val len = length.getUInt(lenTy.length).longValue
          val addr = mutator.newHybrid(allocTy, len)
          results(0).asRef = addr
Kunshan Wang's avatar
Kunshan Wang committed
365 366 367 368 369 370 371
          continueNormally()
        }
      }

      case i @ InstAlloca(allocTy, excClause) => {
        handleOutOfMemory(excClause) {
          val addr = mutator.allocaScalar(curStack.stackMemory, allocTy)
372
          results(0).asIRef = (0L, addr)
Kunshan Wang's avatar
Kunshan Wang committed
373 374 375 376 377 378
          continueNormally()
        }
      }

      case i @ InstAllocaHybrid(allocTy, lenTy, length, excClause) => {
        handleOutOfMemory(excClause) {
379 380 381
          val len = length.getUInt(lenTy.length).longValue
          val addr = mutator.allocaHybrid(curStack.stackMemory, allocTy, len)
          results(0).asIRef = (0L, addr)
Kunshan Wang's avatar
Kunshan Wang committed
382 383 384 385 386
          continueNormally()
        }
      }

      case i @ InstGetIRef(referentTy, opnd) => {
387
        results(0).asIRef = (opnd.asRef, 0L)
Kunshan Wang's avatar
Kunshan Wang committed
388 389 390 391 392 393
        continueNormally()
      }

      case i @ InstGetFieldIRef(ptr, referentTy, index, opnd) => {
        val addrIncr = TypeSizes.fieldOffsetOf(referentTy, index)

394
        incrementBoxIRefOrPointer(ptr, opnd, results(0), addrIncr)
Kunshan Wang's avatar
Kunshan Wang committed
395 396 397 398
        continueNormally()
      }

      case i @ InstGetElemIRef(ptr, referentTy, indTy, opnd, index) => {
399 400
        val ind = index.getSInt(indTy.length).longValue
        val addrIncr = TypeSizes.elemOffsetOf(referentTy, ind)
Kunshan Wang's avatar
Kunshan Wang committed
401

402
        incrementBoxIRefOrPointer(ptr, opnd, results(0), addrIncr)
Kunshan Wang's avatar
Kunshan Wang committed
403 404 405 406
        continueNormally()
      }

      case i @ InstShiftIRef(ptr, referentTy, offTy, opnd, offset) => {
407 408
        val off = offset.getSInt(offTy.length).longValue
        val addrIncr = TypeSizes.shiftOffsetOf(referentTy, off)
Kunshan Wang's avatar
Kunshan Wang committed
409

410
        incrementBoxIRefOrPointer(ptr, opnd, results(0), addrIncr)
Kunshan Wang's avatar
Kunshan Wang committed
411 412 413 414 415 416
        continueNormally()
      }

      case i @ InstGetVarPartIRef(ptr, referentTy, opnd) => {
        val addrIncr = TypeSizes.varPartOffsetOf(referentTy)

417
        incrementBoxIRefOrPointer(ptr, opnd, results(0), addrIncr)
Kunshan Wang's avatar
Kunshan Wang committed
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
        continueNormally()
      }

      case i @ InstLoad(ptr, ord, referentTy, loc, excClause) => {
        val uty = InternalTypePool.unmarkedOf(referentTy)
        val ib = resultBox(0)

        val addr = addressOf(ptr, loc)
        if (addr == 0L) {
          nullRefError(excClause)
        } else {
          MemoryOperations.load(ptr, uty, addr, ib)
          continueNormally()
        }
      }

      case i @ InstStore(ptr, ord, referentTy, loc, newVal, excClause) => {
        val uty = InternalTypePool.unmarkedOf(referentTy)
        val nvb = boxOf(newVal)

        val addr = addressOf(ptr, loc)
        if (addr == 0L) {
          nullRefError(excClause)
        } else {
          MemoryOperations.store(ptr, uty, addr, nvb)
          continueNormally()
        }
      }

      case i @ InstCmpXchg(ptr, weak, ordSucc, ordFail, referentTy, loc, expected, desired, excClause) => {
        val uty = InternalTypePool.unmarkedOf(referentTy)
        val eb = boxOf(expected)
        val db = boxOf(desired)
        val br = resultBox(0)
        val bs = resultBox(1)

        val addr = addressOf(ptr, loc)
        if (addr == 0L) {
          nullRefError(excClause)
        } else {
          val succ = MemoryOperations.cmpXchg(ptr, uty, addr, eb, db, br)
459
          bs.asBoolean = succ
Kunshan Wang's avatar
Kunshan Wang committed
460 461 462 463 464 465 466 467 468 469 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
          continueNormally()
        }
      }

      case i @ InstAtomicRMW(ptr, ord, op, referentTy, loc, opnd, excClause) => {
        val uty = InternalTypePool.unmarkedOf(referentTy)
        val ob = boxOf(opnd)
        val ib = resultBox(0)

        val addr = addressOf(ptr, loc)
        if (addr == 0L) {
          nullRefError(excClause)
        } else {
          MemoryOperations.atomicRMW(ptr, uty, op, addr, ob, ib)
          continueNormally()
        }
      }

      case i @ InstFence(ord) => {
        // No-op in this interpreter
        continueNormally()
      }

      case i @ InstTrap(retTy, excClause, keepAlives) => {
        doTrap(retTy, 0)
      }

      case i @ InstWatchPoint(wpID, retTy, dis, ena, exc, keepAlives) => {
        val isEnabled = microVM.trapManager.isWatchPointEnabled(wpID)

        if (isEnabled) {
          doTrap(retTy, wpID)
        } else {
          branchTo(dis)
        }
      }

497 498 499 500 501 502 503 504 505
      case i @ InstWPBranch(wpID, dis, ena) => {
        val isEnabled = microVM.trapManager.isWatchPointEnabled(wpID)
        if (isEnabled) {
          branchTo(ena)
        } else {
          branchTo(dis)
        }
      }

Kunshan Wang's avatar
Kunshan Wang committed
506 507 508 509 510
      case i @ InstCCall(callConv, funcTy, sig, callee, argList, excClause, keepAlives) => {
        if (callConv != Flag("#DEFAULT")) {
          throw new UvmRefImplException(ctx + "Currently only support the #DEFAULT callConv. %s found.".format(callConv.name))
        }

511
        val addr = callee.asPtr
Kunshan Wang's avatar
Kunshan Wang committed
512 513 514 515 516 517 518 519 520 521

        val argBoxes = argList.map(boxOf)

        val shouldIncrementPC = curStack.callNative(sig, addr, argBoxes)
        if (shouldIncrementPC) {
          continueNormally()
        }
      }

      case i @ InstNewThread(stack, newStackAction, excClause) => {
522
        val newStack = stack.asStack.getOrElse {
Kunshan Wang's avatar
Kunshan Wang committed
523
          throw new UvmRuntimeException(ctx + "Attempt to bind to a NULL stack.")
Kunshan Wang's avatar
Kunshan Wang committed
524
        }
525

526
        val newThread = newStackAction match {
Kunshan Wang's avatar
Kunshan Wang committed
527 528
          case PassValues(argTys, args) => {
            val argBoxes = args.map(boxOf)
529
            microVM.threadStackManager.newThread(newStack, HowToResume.PassValues(argBoxes))
Kunshan Wang's avatar
Kunshan Wang committed
530 531
          }
          case ThrowExc(exc) => {
532
            val excAddr = exc.asRef
533
            microVM.threadStackManager.newThread(newStack, HowToResume.ThrowExc(excAddr))
Kunshan Wang's avatar
Kunshan Wang committed
534
          }
Kunshan Wang's avatar
Kunshan Wang committed
535
        }
536 537
        results(0).asThread = Some(newThread)

538
        continueNormally()
Kunshan Wang's avatar
Kunshan Wang committed
539 540 541 542
      }

      case i @ InstSwapStack(swappee, curStackAction, newStackAction, excClause, keepAlives) => {
        val oldStack = curStack
543
        val newStack = swappee.asStack.getOrElse {
Kunshan Wang's avatar
Kunshan Wang committed
544 545 546
          throw new UvmRuntimeException(ctx + "Swappee must not be NULL.")
        }

Kunshan Wang's avatar
Kunshan Wang committed
547 548 549
        def handleOldStack() = curStackAction match {
          case RetWith(retTys) => {
            unbindRetWith(retTys)
Kunshan Wang's avatar
Kunshan Wang committed
550 551 552 553 554 555 556
          }
          case KillOld() => {
            unbindAndKillStack()
          }
        }

        newStackAction match {
Kunshan Wang's avatar
Kunshan Wang committed
557 558 559 560
          case PassValues(argTys, args) => {
            val argBoxes = args.map(boxOf)
            handleOldStack()
            rebindPassValues(newStack, argBoxes)
Kunshan Wang's avatar
Kunshan Wang committed
561 562
          }
          case ThrowExc(exc) => {
563
            val excBox = boxOf(exc) // need to get the box before the stack is destroyed.
Kunshan Wang's avatar
Kunshan Wang committed
564
            handleOldStack()
565
            rebindThrowExc(newStack, excBox.asRef)
Kunshan Wang's avatar
Kunshan Wang committed
566 567 568
          }
        }
      }
569

Kunshan Wang's avatar
Kunshan Wang committed
570
      case i: InstCommInst => interpretCurrentCommonInstruction()
Kunshan Wang's avatar
Kunshan Wang committed
571 572 573 574 575 576 577 578 579 580 581 582

      case i => {
        throw new UvmRefImplException("Unimplemented instruction %s".format(i.getClass.getName))
      }
    }
  } catch {
    case e: Exception => {
      logger.error(ctx + "Exception thrown while interpreting instruction.")
      throw e
    }
  }
}