/*
 * operators.cpp
 *
 * Author: pgess <v.melnychenko@xreate.org>
 * Created on April 8, 2017, 1:35 PM
 */

#include "operators.h"
#include "llvmlayer.h"
#include "ExternLayer.h"
#include <vector>

using namespace llvm;
using namespace std;

namespace xreate { namespace compilation {

llvm::Value*
PointerArithmetic::add(llvm::Value *left, llvm::Value *right, Context context, const std::string& hintVarDecl){
    LLVMLayer* llvm = context.pass->man->llvm;

    if (left->getType()->isPointerTy() && right->getType()->isIntegerTy()){

        std::vector<llvm::Value*> indexes{right};
        //{llvm::ConstantInt::get(llvm::Type::getInt32Ty(llvm::getGlobalContext()), 0)};
        //indexes.push_back(right);

        return llvm->builder.CreateGEP(left, llvm::ArrayRef<llvm::Value*>(indexes), hintVarDecl);
    }

    return nullptr;
}


llvm::Value*
StructUpdate::add(const Expression& left, llvm::Value *leftRaw, const Expression& right, Context context, const std::string& hintVarDecl){\
    if (!(right.__state == Expression::COMPOUND && right.op == Operator::LIST_NAMED)){
        return nullptr;
    }

    PassManager* man = context.pass->man;

    ExpandedType tyOperandLeft = man->root->getType(left);

    const std::vector<string> fieldsFormal = (tyOperandLeft.get().__operator == TypeOperator::CUSTOM)?
        man->llvm->layerExtern->getStructFields(man->llvm->layerExtern->lookupType(tyOperandLeft.get().__valueCustom))
        : tyOperandLeft.get().fields;

    std::map<std::string, size_t> indexFields;
    for(size_t i=0, size = fieldsFormal.size(); i<size; ++i){
        indexFields.emplace(fieldsFormal[i], i);
    }

    llvm::Value* result = leftRaw;
    for (size_t i=0; i<right.operands.size(); ++i){
        const Expression& value = right.operands.at(i);
        llvm::Value* valueRaw = context.scope->process(value, right.bindings.at(i));
        unsigned int fieldId = indexFields.at(right.bindings.at(i));

        result = man->llvm->builder.CreateInsertValue(result, valueRaw, llvm::ArrayRef<unsigned>({fieldId}));
    }

    return result;
}

} }