/* 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 "HIR.h"
#include "BytecodeEmitter.h"
#include "../Heap-inl.h"
#include "../Handles-inl.h"

using namespace ke;

class HIRTranslator : public HIRVisitor
{
  public:
    HIRTranslator(Zone *zone, BytecodeEmitter &emitter)
      : zone_(zone),
        emitter_(emitter)
    {
    }

    void translate(HIR *hir) {
        hir->accept(this);
    }

    void visitFloat(HFloat *hir);
    void visitInteger(HInteger *hir);
    void visitCall(HCall *call);
    void visitStore(HStore *store);
    void visitBinary(HBinary *binary);
    void visitLocal(HLocal *local);
    void visitGlobal(HGlobal *global);
    void visitConvert(HConvert *convert);
    void visitIndex(HIndex *index);

  private:
    Zone *zone_;
    BytecodeEmitter &emitter_;
};

#define __ emitter_.

void
HIRTranslator::visitFloat(HFloat *hir)
{
    __ float_(hir->value());
}

void
HIRTranslator::visitInteger(HInteger *hir)
{
    __ int_(hir->value());
}

void
HIRTranslator::visitCall(HCall *call)
{
    Local<FunctionType> fun(zone_, FunctionType::cast(call->callee()->type()));
    
    assert(call->args()->length() == fun->parameters()->length());

    unsigned argc = call->args()->length();

    for (size_t i = call->args()->length() - 1; i < call->args()->length(); i--) {
        HIR *hir = call->args()->at(i);
        hir->accept(this);
    }

    call->callee()->accept(this);
    __ call(fun, argc);
}

void
HGlobal::bind(HIRVisitor *visitor, BytecodeEmitter &emitter_)
{
}

void
HGlobal::hold(BytecodeEmitter &emitter_)
{
}

void
HGlobal::store(BytecodeEmitter &emitter_)
{
    __ setglobal(sym_);
}

void
HGlobal::load(BytecodeEmitter &emitter_)
{
    __ getglobal(sym_);
}

void
HLocal::bind(HIRVisitor *visitor, BytecodeEmitter &emitter_)
{
    if (sym_->type()->isReference())
        __ getlocal(sym_);
}

void
HLocal::hold(BytecodeEmitter &emitter_)
{
    if (sym_->type()->isReference())
        __ dup();
}

void
HLocal::store(BytecodeEmitter &emitter_)
{
    if (sym_->type()->isReference())
        __ setref(sym_->type()->contained_ref());
    else
        __ setlocal(sym_);
}

void
HLocal::load(BytecodeEmitter &emitter_)
{
    if (sym_->type()->isReference())
        __ getref(sym_->type());
    else
        __ getlocal(sym_);
}

void
HIndex::bind(HIRVisitor *visitor, BytecodeEmitter &emitter_)
{
    left_->accept(visitor);
    right_->accept(visitor);
}

void
HIndex::hold(BytecodeEmitter &emitter_)
{
    __ dup2();
}

void
HIndex::store(BytecodeEmitter &emitter_)
{
    __ setelem(type());
}

void
HIndex::load(BytecodeEmitter &emitter_)
{
    __ getelem(type());
}

void
HIRTranslator::visitLocal(HLocal *local)
{
    local->bind(this, emitter_);
    local->load(emitter_);
}

void
HIRTranslator::visitIndex(HIndex *index)
{
    index->bind(this, emitter_);
    index->load(emitter_);
}

void
HIRTranslator::visitGlobal(HGlobal *global)
{
    __ getglobal(global->sym());
}

static inline Opcode
TokenToOpcode(TokenKind kind)
{
    switch (kind) {
      case TOK_PLUS:
      case TOK_ASSIGN_ADD:
      case TOK_INCREMENT:
        return OP_ADD;
      case TOK_MINUS:
      case TOK_ASSIGN_SUB:
      case TOK_DECREMENT:
        return OP_SUB;
      case TOK_STAR:
      case TOK_ASSIGN_MUL:
        return OP_MUL;
      case TOK_SLASH:
      case TOK_ASSIGN_DIV:
        return OP_DIV;
      case TOK_PERCENT:
      case TOK_ASSIGN_MOD:
        return OP_MOD;
      case TOK_SHR:
      case TOK_ASSIGN_SHR:
        return OP_SHR;
      case TOK_USHR:
      case TOK_ASSIGN_USHR:
        return OP_USHR;
      case TOK_SHL:
      case TOK_ASSIGN_SHL:
        return OP_SHL;
      case TOK_BITAND:
      case TOK_ASSIGN_BITAND:
        return OP_BITAND;
      case TOK_BITOR:
      case TOK_ASSIGN_BITOR:
        return OP_BITOR;
      case TOK_GT:
          return OP_GT;
      case TOK_GE:
          return OP_GE;
      case TOK_LT:
          return OP_LT;
      case TOK_LE:
          return OP_LE;
      case TOK_EQUALS:
          return OP_EQ;
      case TOK_NOTEQUALS:
          return OP_NE;
      default:
        assert(kind == TOK_BITXOR);
        return OP_BITXOR;
    }
}

void
HIRTranslator::visitStore(HStore *store)
{
    store->lval()->bind(this, emitter_);
    if (store->kind() == TOK_ASSIGN) {
        store->rval()->accept(this);
    } else {
        // Advanced case: dup the ref, load, op, store.
        store->lval()->hold(emitter_);
        store->lval()->load(emitter_);
        store->rval()->accept(this);
        __ binary(TokenToOpcode(store->kind()));
    }
    store->lval()->store(emitter_);
}

void
HIRTranslator::visitBinary(HBinary *binary)
{
    binary->left()->accept(this);
    binary->right()->accept(this);

    // We define three sets of math operators:
    //
    //  (1) ADD, SUB, MUL, DIV, MOD, which take two equal types and produce
    //      the same type.
    //  (2) LT, LE, GE, GT, EQ, NE, which take two equal types and produce
    //      a boolean.
    //  (3) SHL, SR, USHR, BITAND, BITOR, BITXOR, BITNOT, which take two
    //      equal integer types and return that integer type.
    //
    Opcode op = TokenToOpcode(binary->token());

    if (op >= OP_ADD && op <= OP_NE) {
        if (binary->type()->isFloat())
            op = Opcode(int(op) + int(OP_ADD_F - OP_ADD));
    } else {
        assert(binary->type()->isInt32());
    }

    __ binary(op);
}

void
HIRTranslator::visitConvert(HConvert *convert)
{
    convert->in()->accept(this);
    __ unary(convert->opcode());
}

void
ke::EmitHIR(Zone *zone, BytecodeEmitter &emitter, HIR *hir)
{
    HIRTranslator translator(zone, emitter);
    translator.translate(hir);
}
