/* vim: set ts=4 sw=4 tw=99 et:
 *
 * Copyright (C) 2012 David Anderson
 *
 * This file is part of JITCraft.
 *
 * JITCraft is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option)
 * any later version.
 * 
 * Foobar is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * JITCraft. If not, see http://www.gnu.org/licenses/.
 */
#include <string.h>
#include "Interpreter.h"
#include "Modules.h"
#include "Zone.h"
#include "Types.h"
#include "Array.h"
#include "Reference.h"
#include "Strings.h"
#include "Environments.h"
#include "Structures.h"
#include "NativeTable.h"
#include "Heap-inl.h"

using namespace ke;

#define PUSH_I32(top, value)    \
    do {                        \
        top.sp->i32 = value;    \
        top.sp++;               \
   } while (0)

#define PUSH_F(top, value)      \
    do {                        \
        top.sp->f = value;      \
        top.sp++;               \
   } while (0)

static inline int
POP_I32(Top &top)
{
    int value = top.sp[-1].i32;
    top.sp--;
    return value;
}

static inline float
POP_F(Top &top)
{
    float value = top.sp[-1].f;
    top.sp--;
    return value;
}

// Pawn's original semantics specify some kind of floor operation, so
// (8 / -3 == -3) and (-8 / 3 == -1). The SourcePawn 1 compiler (spcomp) uses
// the upstream algorithm when constant folding. However the SourcePawn 1 JIT
// does not. My guess is that Borja freaked out seeing the 13-instruction x86
// sequence necessary to get this functionality (I vaguely recall a thread
// where we discussed this with Mark Peter? But the ITB forums are gone...),
// and we just decided to break the damn thing. So SP1 was inconsistent, but
// we are not. And for completeness, we assert that the C compiler does the
// right thing, since C89 leaves it unspecified.
STATIC_ASSERT(8 / -3 == -2);
STATIC_ASSERT(-8 / 3 == -2);

static inline bool
PushNewRef(Zone *zone, Top &top, void *location, Heap::Tenure tenure)
{
    Reference *ref = Reference::NewStack(zone, location, tenure);
    if (!ref)
        return false;
    top.sp->ref = ref;
    top.sp++;
    return true;
}

static bool CopyStruct(Zone *zone, Handle<Struct> left, Handle<Struct> right);

static bool
ChangeArrayLength(Zone *zone, Handle<Array> source, Handle<Array> dest)
{
    return true;
}

// Even though this function can fail, we immediately bail out, so it doesn't
// matter if we've leaving things unrooted.
static bool
CopyArray(Zone *zone, Handle<Array> dest, Handle<Array> source)
{
    if (source->length() != dest->length()) {
        if (!ChangeArrayLength(zone, source, dest))
            return false;
    }

    Local<Type> contained(zone, source->type()->contained());
    if (contained->isArray() && contained->isFixedLength()) {
        assert(dest->type()->contained()->isArray());
        assert(source->length() == dest->length());

        Local<Array> left(zone);
        Local<Array> right(zone);
        for (unsigned i = 0; i < source->length(); i++) {
            left = Array::cast(dest->readObject(i));
            right = Array::cast(source->readObject(i));
            if (!CopyArray(zone, left, right))
                return false;
        }
        return true;
    }
    
    if (contained->isStruct()) {
        assert(dest->type()->contained() == contained);
        assert(source->length() == dest->length());

        Local<Struct> left(zone);
        Local<Struct> right(zone);
        for (unsigned i = 0; i < source->length(); i++) {
            left = Struct::cast(dest->readObject(i));
            right = Struct::cast(source->readObject(i));
            if (!CopyStruct(zone, left, right))
                return false;
        }
        return true;
    }

    if (contained->isTraceable()) {
        for (unsigned i = 0; i < source->length(); i++)
            dest->writeObject(zone, i, source->readObject(i));
        return true;
    }

    assert(contained->pod() == dest->type()->contained()->pod());
    assert(contained->pod() == PrimitiveType_Char
           ? source->length() <= dest->length()
           : source->length() == dest->length());

    assert(dest->length());
    memcpy(dest->bytes(), source->bytes(), source->length() * Array::SizeForElement(dest->type()));
    return true;
}

static void
GetElement(Array *array, int index, LocalSlot *vp)
{
    if (array->type()->contained()->isTraceable()) {
        vp->obj = array->readObject(index);
        return;
    }

    switch (array->type()->contained()->pod()) {
      case PrimitiveType_Float:
        vp->f = array->readFloat(index);
        break;

      case PrimitiveType_Char:
        vp->i32 = array->readChar(index);
        break;

      default:
        assert(array->type()->contained()->pod() == PrimitiveType_Int32);
        vp->i32 = array->readInt32(index);
        break;
    }
}

static void
SetElement(Zone *zone, Array *array, int index, const LocalSlot &v)
{
    if (array->type()->contained()->isTraceable()) {
        array->writeObject(zone, index, v.obj);
        return;
    }

    switch (array->type()->contained()->pod()) {
      case PrimitiveType_Float:
        array->writeFloat(index, v.f);
        break;

      case PrimitiveType_Char:
        array->writeChar(index, v.i32);
        break;

      default:
        assert(array->type()->contained()->pod() == PrimitiveType_Int32);
        array->writeInt32(index, v.i32);
        break;
    }
}

static void
FetchField(Struct *obj, Descriptor *desc, LocalSlot *vp)
{
    // :TODO: assert no GC.
    if (desc->type()->isTraceable()) {
        vp->obj = obj->get<Object *>(desc);
        return;
    }

    switch (desc->type()->pod()) {
      case PrimitiveType_Float:
        vp->f = obj->get<float>(desc);
        break;

      default:
        assert(desc->type()->pod() == PrimitiveType_Int32);
        vp->i32 = obj->get<int>(desc);
        break;
    }
}

static void
GetField(Struct *obj, unsigned index, LocalSlot *vp)
{
    StructType *type = StructType::cast(obj->map()->type());
    Descriptor *desc = Descriptor::cast(type->fields()->at(index));
    FetchField(obj, desc, vp);
}

static void
GetGlobal(Zone *zone, Handle<Struct> obj, Handle<String> name, LocalSlot *vp)
{
    Local<StructType> type(zone, StructType::cast(obj->map()->type()));
    Local<Descriptor> desc(zone, type->lookupField(name, NULL));
    FetchField(obj, desc, vp);
}

static void
StoreField(Zone *zone, Struct *obj, Descriptor *desc, const LocalSlot &v)
{
    // :TODO: assert no GC.
    if (desc->type()->isTraceable()) {
        obj->set(zone, desc, v.obj);
        return;
    }

    switch (desc->type()->pod()) {
      case PrimitiveType_Float:
        obj->set<float>(desc, v.f);
        break;

      default:
        assert(desc->type()->pod() == PrimitiveType_Int32);
        obj->set<int>(desc, v.i32);
        break;
    }
}

static void
SetField(Zone *zone, Struct *obj, unsigned index, const LocalSlot &v)
{
    StructType *type = StructType::cast(obj->map()->type());
    Descriptor *desc = Descriptor::cast(type->fields()->at(index));
    StoreField(zone, obj, desc, v);
}

static void
SetGlobal(Zone *zone, Handle<Struct> obj, Handle<String> name, LocalSlot &v)
{
    Local<StructType> type(zone, StructType::cast(obj->map()->type()));
    Local<Descriptor> desc(zone, type->lookupField(name, NULL));
    StoreField(zone, obj, desc, v);
}

// Even though this function can fail, we immediately bail out, so it doesn't
// matter if we've leaving things unrooted.
static bool
CopyStruct(Zone *zone, Handle<Struct> left, Handle<Struct> right)
{
    assert(left->map()->type() == right->map()->type());

    Local<StructType> type(zone, StructType::cast(left->map()->type()));
    Local<Struct> leftStruct(zone);
    Local<Struct> rightStruct(zone);
    Local<Array> leftArray(zone);
    Local<Array> rightArray(zone);
    for (unsigned i = 0; i < type->fields()->length(); i++) {
        Descriptor *desc = Descriptor::cast(type->fields()->at(i));

        LocalSlot rval;
        FetchField(right, desc, &rval);

        // If the field is a struct, we need to deep-copy.
        if (desc->type()->isStruct()) {
            LocalSlot lval;

            FetchField(left, desc, &lval);
            leftStruct = Struct::cast(lval.obj);
            rightStruct = Struct::cast(rval.obj);
            if (!CopyStruct(zone, leftStruct, rightStruct))
                return false;
        } else if (desc->type()->isArray()) {
            LocalSlot lval;

            FetchField(left, desc, &lval);
            leftArray = Array::cast(lval.obj);
            rightArray = Array::cast(rval.obj);
            if (!CopyArray(zone, leftArray, rightArray))
                return false;
        } else {
            StoreField(zone, left, desc, rval);
        }
    }

    return true;
}

static bool
InvokeNative(Zone *zone, Handle<Native> native, void *identity, LocalSlot *args, unsigned argc,
             int *result)
{
    NativeArgs guard;

    void *address = zone->nativeTable()->address(native->index());
    if (!address) {
        Local<String> name(zone, zone->nativeTable()->name(native->index()));
        zone->reportError(Message_NativeNotBound, name->chars());
        return false;
    }

    if (!zone->stack().pushNativeFrame(native, guard, argc + 1))
        return false;

    intptr_t *cells = guard.args();

    // params[0] == argc, in ISPE
    cells[0] = argc;

    // Pass the formal arguments.
    Local<FunctionType> type(zone, native->type());
    Local<Type> param(zone);
    for (unsigned i = 0; i < type->parameters()->length(); i++) {
        param = type->parameterAt(i);
        
        // For floats, we rely on the aliasing of |i32| and |f|.
        LocalSlot &arg = args[-int(i) - 1];
        if (param->isInt32() || param->isFloat()) {
            cells[i + 1] = arg.i32;
        } else if (param->isReference()) {
            cells[i + 1] = reinterpret_cast<intptr_t>(arg.ref->location());
        } else {
            assert(param->isArray());
            cells[i + 1] = reinterpret_cast<intptr_t>(arg.array->bytes());
        }
    }

    // For variadic arguments, the compiler left either arrays or references.
    for (unsigned i = type->parameters()->length(); i < argc; i++) {
        LocalSlot &arg = args[-int(i) - 1];

        if (arg.obj->is(MapKind_Reference)) {
            cells[i + 1] = reinterpret_cast<intptr_t>(arg.ref->location());
        } else {
            assert(arg.obj->is(MapKind_Array));
            cells[i + 1] = reinterpret_cast<intptr_t>(arg.array->bytes());
        }
    }

    typedef intptr_t (*INVOKE)(void *, intptr_t *);
    INVOKE invoke = (INVOKE)address;
    *result = invoke(identity, cells);

    return !zone->hasPendingException();
}

bool
ke::Interpret(Zone *zone, Frame *entryFrame, LocalSlot *result)
{
    Top &top = *zone->stack().top();
    if (!entryFrame)
        entryFrame = top.fp;

    LocalSlot *locals = entryFrame->locals();

    for (;;) {
        Opcode op = Opcode(*top.pc);

        if (OpcodeInfo[op].nuses > 0)
            assert(top.sp - OpcodeInfo[op].nuses >= top.fp->stackBase());

        switch (op) {

case OP_NOP:
    break;

case OP_INT:
    PUSH_I32(top, READ_INT32(top.pc));
    break;

case OP_FLOAT:
    PUSH_F(top, READ_FLOAT(top.pc));
    break;

case OP_RETURN:
case OP_RETURNVOID:
case OP_STOP:
{
    if (op == OP_RETURN)
        *result = *--top.sp;

    if (top.fp == entryFrame)
        goto done;

    // This must not GC.
    zone->stack().popInlineFrame();
    locals = top.fp->locals();

    if (op == OP_RETURN)
        *top.sp++ = *result;

    top.pc += OpcodeInfo[*top.pc].length;
    continue;
}

case OP_POP:
{
    top.sp--;
    break;
}

case OP_JT:
{
    int value = POP_I32(top);
    if (value) {
        top.pc += READ_INT32(top.pc);
        continue;
    }
    break;
}

case OP_JF:
{
    int value = POP_I32(top);
    if (!value) {
        top.pc += READ_INT32(top.pc);
        continue;
    }
    break;
}

case OP_JUMP:
    top.pc += READ_INT32(top.pc);
    continue;

case OP_GETLOCAL:
{
    unsigned slot = READ_UINT32(top.pc);
    assert(slot < top.fp->code()->nlocals());
    *top.sp++ = locals[slot];
    break;
}

case OP_SETLOCAL:
{
    unsigned slot = READ_UINT32(top.pc);
    assert(slot < top.fp->code()->nlocals());
    locals[slot] = top.sp[-1];
    break;
}

case OP_ADD:
{
    top.sp[-2].i32 = top.sp[-2].i32 + top.sp[-1].i32;
    top.sp--;
    break;
}

case OP_SUB:
{
    top.sp[-2].i32 = top.sp[-2].i32 - top.sp[-1].i32;
    top.sp--;
    break;
}

case OP_MUL:
{
    top.sp[-2].i32 = top.sp[-2].i32 * top.sp[-1].i32;
    top.sp--;
    break;
}

case OP_DIV:
{
    if (top.sp[-1].i32 == 0) {
        zone->reportError(Message_IntegerDivideByZero);
        goto error;
    }
    top.sp[-2].i32 = top.sp[-2].i32 / top.sp[-1].i32;
    top.sp--;
    break;
}

case OP_MOD:
{
    if (top.sp[-1].i32 == 0) {
        zone->reportError(Message_IntegerDivideByZero);
        goto error;
    }
    top.sp[-2].i32 = top.sp[-2].i32 % top.sp[-1].i32;
    top.sp--;
    break;
}

case OP_LT:
{
    top.sp[-2].i32 = top.sp[-2].i32 < top.sp[-1].i32;
    top.sp--;
    break;
}

case OP_LE:
{
    top.sp[-2].i32 = top.sp[-2].i32 <= top.sp[-1].i32;
    top.sp--;
    break;
}

case OP_GT:
{
    top.sp[-2].i32 = top.sp[-2].i32 > top.sp[-1].i32;
    top.sp--;
    break;
}

case OP_GE:
{
    top.sp[-2].i32 = top.sp[-2].i32 >= top.sp[-1].i32;
    top.sp--;
    break;
}

case OP_EQ:
{
    top.sp[-2].i32 = (top.sp[-2].i32 == top.sp[-1].i32);
    top.sp--;
    break;
}

case OP_NE:
{
    top.sp[-2].i32 = (top.sp[-2].i32 != top.sp[-1].i32);
    top.sp--;
    break;
}

case OP_ADD_F:
{
    top.sp[-2].f = top.sp[-2].f + top.sp[-1].f;
    top.sp--;
    break;
}

case OP_SUB_F:
{
    top.sp[-2].f = top.sp[-2].f - top.sp[-1].f;
    top.sp--;
    break;
}

case OP_MUL_F:
{
    top.sp[-2].f = top.sp[-2].f * top.sp[-1].f;
    top.sp--;
    break;
}

case OP_DIV_F:
{
    top.sp[-2].f = top.sp[-2].f / top.sp[-1].f;
    top.sp--;
    break;
}

case OP_LT_F:
{
    top.sp[-2].f = top.sp[-2].f < top.sp[-1].f;
    top.sp--;
    break;
}

case OP_LE_F:
{
    top.sp[-2].f = top.sp[-2].f <= top.sp[-1].f;
    top.sp--;
    break;
}

case OP_GT_F:
{
    top.sp[-2].f = top.sp[-2].f > top.sp[-1].f;
    top.sp--;
    break;
}

case OP_GE_F:
{
    top.sp[-2].f = top.sp[-2].f >= top.sp[-1].f;
    top.sp--;
    break;
}

case OP_EQ_F:
{
    top.sp[-2].i32 = (top.sp[-2].f == top.sp[-1].f);
    top.sp--;
    break;
}

case OP_NE_F:
{
    top.sp[-2].i32 = (top.sp[-2].f != top.sp[-1].f);
    top.sp--;
    break;
}

case OP_SHL:
{
    top.sp[-2].i32 = top.sp[-2].i32 << top.sp[-1].i32;
    top.sp--;
    break;
}

case OP_SHR:
{
    top.sp[-2].i32 = top.sp[-2].i32 >> top.sp[-1].i32;
    top.sp--;
    break;
}

case OP_USHR:
{
    top.sp[-2].i32 = unsigned(top.sp[-2].i32) << unsigned(top.sp[-1].i32);
    top.sp--;
    break;
}

case OP_BITAND:
{
    top.sp[-2].i32 = top.sp[-2].i32 & top.sp[-1].i32;
    top.sp--;
    break;
}

case OP_BITOR:
{
    top.sp[-2].i32 = top.sp[-2].i32 | top.sp[-1].i32;
    top.sp--;
    break;
}

case OP_BITXOR:
{
    top.sp[-2].i32 = top.sp[-2].i32 ^ top.sp[-1].i32;
    top.sp--;
    break;
}

case OP_BITNOT:
{
    top.sp[-1].i32 = ~top.sp[-1].i32;
    break;
}

case OP_NOT:
{
    top.sp[-1].i32 = top.sp[-1].i32 ? 0 : 1;
    break;
}

case OP_NOT_F:
{
    top.sp[-1].i32 = top.sp[-1].f ? 0 : 1;
    break;
}

case OP_NEG:
{
    top.sp[-1].i32 = -top.sp[-1].i32;
    break;
}

case OP_NEG_F:
{
    top.sp[-1].f = -top.sp[-1].f;
    break;
}

case OP_CALL:
{
    Local<Function> newFun(zone, Function::cast(top.sp[-1].obj));
    top.sp--;

    if (!zone->stack().pushInlineFrame(newFun))
        goto error;

    locals = top.fp->locals();
    continue;
}

case OP_GETARG:
{
    unsigned slot = READ_UINT32(top.pc);
    *top.sp++ = top.fp->arg(slot);
    break;
}

case OP_SETARG:
{
    unsigned slot = READ_UINT32(top.pc);
    top.fp->arg(slot) = top.sp[-1];
    break;
}

case OP_GETELEM:
{
    Array *array = Array::cast(top.sp[-2].obj);
    int index = top.sp[-1].i32;

    if (index < 0 || unsigned(index) >= array->length()) {
        zone->reportError(Message_ArrayIndexOutOfBounds, index, array->length());
        goto error;
    }

    GetElement(array, index, &top.sp[-2]);
    top.sp--;
    break;
}

case OP_SETELEM:
{
    Array *array = Array::cast(top.sp[-3].obj);
    int index = top.sp[-2].i32;

    if (index < 0 || unsigned(index) >= array->length()) {
        zone->reportError(Message_ArrayIndexOutOfBounds, index, array->length());
        goto error;
    }

    SetElement(zone, array, index, top.sp[-1]);
    top.sp[-3] = top.sp[-1];
    top.sp -= 2;
    break;
}

case OP_CVT_I2F:
{
    int ival = POP_I32(top);
    float fval = (float)ival;
    PUSH_F(top, fval);
    break;
}

case OP_NEWFIXED:
{
    Heap::Tenure tenure = (Heap::Tenure)top.pc[1];
    Local<ArrayMap> map(zone, ArrayMap::cast(top.fp->code()->map(READ_UINT32(top.pc + 1))));
    Array *array = Array::NewFixed(zone, map, tenure);
    if (!array)
        goto error;
    top.sp->obj = array;
    top.sp++;
    break;
}

case OP_NEWEMPTY:
{
    Heap::Tenure tenure = (Heap::Tenure)top.pc[1];
    Local<ArrayMap> map(zone, ArrayMap::cast(top.fp->code()->map(READ_UINT32(top.pc + 1))));
    Array *array = Array::NewEmpty(zone, map, tenure);
    if (!array)
        goto error;
    top.sp->obj = array;
    top.sp++;
    break;
}

case OP_NEWSIZED:
{
    Heap::Tenure tenure = (Heap::Tenure)top.pc[1];
    Local<ArrayMap> map(zone, ArrayMap::cast(top.fp->code()->map(READ_UINT32(top.pc + 1))));
    assert(map->type()->levels() < MAX_ARRAY_DEPTH);

    int dims[MAX_ARRAY_DEPTH];
    for (unsigned i = map->type()->levels() - 1; i < map->type()->levels(); i--)
        dims[i] = POP_I32(top);

    Array *array = Array::NewSized(zone, map, dims, tenure);
    if (!array)
        goto error;
    top.sp->obj = array;
    top.sp++;
    break;
}

case OP_NEWSTRUCT:
{
    Heap::Tenure tenure = (Heap::Tenure)top.pc[1];
    Local<StructMap> map(zone, StructMap::cast(top.fp->code()->map(READ_UINT32(top.pc + 1))));
    top.sp->obj = Struct::New(zone, map, tenure);
    if (!top.sp->obj)
        goto error;
    top.sp++;
    break;
}

case OP_SAVELIFO:
{
    unsigned slot = READ_UINT32(top.pc);
    locals[slot].address = zone->heap().lifoPosition();
    break;
}

case OP_UNWINDLIFO:
{
    unsigned slot = READ_UINT32(top.pc);
    zone->heap().unwindLifo(locals[slot].address);
    break;
}

case OP_VARREF_LIFO:
{
    unsigned slot = READ_UINT32(top.pc);
    if (!PushNewRef(zone, top, &locals[slot], Heap::Tenure_Stack))
        goto error;
    break;
}

case OP_ARGREF_LIFO:
{
    unsigned slot = READ_UINT32(top.pc);
    if (!PushNewRef(zone, top, &top.fp->arg(slot), Heap::Tenure_Stack))
        goto error;
    break;
}

case OP_SLOTREF_LIFO:
{
    Reference *ref = Reference::NewStack(zone, top.sp[-1], Heap::Tenure_Stack);
    if (!ref)
        goto error;
    top.sp[-1].ref = ref;
    break;
}

case OP_GETREF_I:
{
    top.sp[-1].i32 = top.sp[-1].ref->getInt();
    break;
}

case OP_SETREF_I:
{
    top.sp[-2].ref->setInt(top.sp[-1].i32);
    top.sp[-2].i32 = top.sp[-1].i32;
    top.sp--;
    break;
}

case OP_GETREF_F:
{
    top.sp[-1].f = top.sp[-1].ref->getFloat();
    break;
}

case OP_SETREF_F:
{
    top.sp[-2].ref->setFloat(top.sp[-1].f);
    top.sp[-2].f = top.sp[-1].f;
    break;
}

case OP_OBJECT:
{
    top.sp->obj = top.fp->code()->object(READ_UINT32(top.pc));
    top.sp++;
    break;
}

case OP_COPYARRAY:
{
    // Note for this assignment opcode, we return the left-hand side, not the
    // right, since in this case the result of the expression could be different.
    Local<Array> left(zone, Array::cast(top.sp[-2].array));
    Local<Array> right(zone, Array::cast(top.sp[-1].array));
    if (!CopyArray(zone, left, right))
        goto error;
    top.sp--;
    break;
}

case OP_DUP:
{
    top.sp++;
    top.sp[-1] = top.sp[-2];
    break;
}

case OP_DUP2:
{
    top.sp += 2;
    top.sp[-2] = top.sp[-4];
    top.sp[-1] = top.sp[-3];
    break;
}

case OP_SWAP:
{
    LocalSlot slot = top.sp[-2];
    top.sp[-2] = top.sp[-1];
    top.sp[-1] = slot;
    break;
}

case OP_ROLL3:
{
    LocalSlot slot = top.sp[-3];
    top.sp[-3] = top.sp[-2];
    top.sp[-2] = top.sp[-1];
    top.sp[-1] = slot;
    break;
}

case OP_PICK2:
{
    top.sp++;
    top.sp[-1] = top.sp[-3];
    break;
}

case OP_PICK3:
{
    top.sp++;
    top.sp[-1] = top.sp[-4];
    break;
}

case OP_CALLNATIVE:
{
    unsigned argc = READ_UINT32(top.pc);

    Local<Native> native(zone, Native::cast(top.sp[-1].obj));
    top.sp--;

    int result;
    void *nativeIdentity = top.fp->code()->module()->nativeIdentity();
    if (!InvokeNative(zone, native, nativeIdentity, top.sp, argc, &result))
        goto error;

    top.sp -= argc;
    PUSH_I32(top, result);
    break;
}

case OP_BITS_I2F:
case OP_BITS_F2I:
{
    // Because the stack is a union, these are actually no-ops in the
    // interpreter.
    break;
}

case OP_TRUE:
{
    top.sp++;
    top.sp[-1].i32 = 1;
    break;
}

case OP_FALSE:
{
    top.sp++;
    top.sp[-1].i32 = 0;
    break;
}

case OP_GETFIELD:
{
    Struct *obj = Struct::cast(top.sp[-1].obj);
    GetField(obj, READ_UINT32(top.pc), &top.sp[-1]);
    break;
}

case OP_SETFIELD:
{
    Struct *obj = Struct::cast(top.sp[-2].obj);
    SetField(zone, obj, READ_UINT32(top.pc), top.sp[-1]);
    top.sp[-2] = top.sp[-1];
    top.sp--;
    break;
}

case OP_COPYSTRUCT:
{
    Local<Struct> left(zone, Struct::cast(top.sp[-2].obj));
    Local<Struct> right(zone, Struct::cast(top.sp[-1].obj));
    if (!CopyStruct(zone, left, right))
        goto error;
    top.sp[-2].obj = top.sp[-1].obj;
    top.sp--;
    break;
}

case OP_TABLESWITCH:
{
    int value = top.sp[-1].i32;
    int low = READ_TABLESWITCH_LOW(top.pc);
    int high = READ_TABLESWITCH_HIGH(top.pc);

    top.sp--;

    unsigned index = unsigned(value - low);
    unsigned tablesize = TableSwitchEntries(low, high);
    if (index < tablesize) {
        top.pc += OP_TABLESWITCH_LENGTH + OP_JUMP_LENGTH;
        top.pc += index * OP_JUMP_LENGTH;
        continue;
    }
    break;
}

case OP_SIZEOF:
{
    Array *array = Array::cast(top.sp[-1].obj);
    top.sp[-1].i32 = array->length();
    break;
}

case OP_PUBLIC:
{
    Local<Function> fun(zone, Function::cast(top.sp[-1].obj));
    zone->registerPublic(fun);
    top.sp--;
    break;
}

case OP_SETGLOBAL:
{
    Local<Code> code(zone, top.fp->code());
    Local<Struct> obj(zone, code->module()->globals());
    Local<String> name(zone, String::cast(code->strings()->at(READ_UINT32(top.pc))));
    SetGlobal(zone, obj, name, top.sp[-1]);
    break;
}

case OP_GETGLOBAL:
{
    Local<Code> code(zone, top.fp->code());
    Local<Struct> obj(zone, code->module()->globals());
    Local<String> name(zone, String::cast(code->strings()->at(READ_UINT32(top.pc))));
    GetGlobal(zone, obj, name, top.sp);
    top.sp++;
    break;
}

default:
    assert(false);
    return false;

        }

        top.pc += OpcodeInfo[op].length;
        assert(top.sp >= top.fp->stackBase());
    }

done:
    return true;

error:
    // Unwind frames until we can continue.
    while (top.fp != entryFrame)
        zone->stack().popInlineFrame();
    return false;
}
