/*
 * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code 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
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */



package jdk.tools.jaotc;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

import org.graalvm.compiler.code.DataSection;
import org.graalvm.compiler.hotspot.meta.HotSpotConstantLoadAction;

import jdk.tools.jaotc.binformat.BinaryContainer;
import jdk.tools.jaotc.binformat.Relocation;
import jdk.tools.jaotc.binformat.Relocation.RelocType;
import jdk.tools.jaotc.binformat.Symbol;
import jdk.tools.jaotc.binformat.Symbol.Binding;
import jdk.tools.jaotc.binformat.Symbol.Kind;
import jdk.vm.ci.code.TargetDescription;
import jdk.vm.ci.code.site.ConstantReference;
import jdk.vm.ci.code.site.DataPatch;
import jdk.vm.ci.code.site.DataSectionReference;
import jdk.vm.ci.code.site.Reference;
import jdk.vm.ci.hotspot.HotSpotConstantPoolObject;
import jdk.vm.ci.hotspot.HotSpotMetaspaceConstant;
import jdk.vm.ci.hotspot.HotSpotObjectConstant;
import jdk.vm.ci.hotspot.HotSpotResolvedObjectType;
import jdk.vm.ci.hotspot.HotSpotSentinelConstant;
import jdk.vm.ci.meta.VMConstant;

final class DataPatchProcessor {

    private final TargetDescription target;

    private final BinaryContainer binaryContainer;

    DataPatchProcessor(DataBuilder dataBuilder) {
        this.target = dataBuilder.getBackend().getTarget();
        this.binaryContainer = dataBuilder.getBinaryContainer();
    }

    /**
     * Process a {@link DataPatch} generated by the compiler and create all needed binary section
     * constructs.
     */
    void process(CompiledMethodInfo methodInfo, DataPatch dataPatch) {
        Reference reference = dataPatch.reference;
        if (reference instanceof ConstantReference) {
            processConstantReference(dataPatch, methodInfo);
        } else if (reference instanceof DataSectionReference) {
            processDataSectionReference(dataPatch, methodInfo);
        } else {
            throw new InternalError("Unknown data patch reference: " + reference);
        }
    }

    private void processConstantReference(DataPatch dataPatch, CompiledMethodInfo methodInfo) {
        HotSpotConstantLoadAction action = (HotSpotConstantLoadAction) dataPatch.note;
        ConstantReference constantReference = (ConstantReference) dataPatch.reference;
        assert action != null : "action should be set";

        VMConstant constant = constantReference.getConstant();
        String targetSymbol = null;
        String gotName = null;
        if (constant instanceof HotSpotMetaspaceConstant) {
            HotSpotMetaspaceConstant metaspaceConstant = (HotSpotMetaspaceConstant) constant;
            if (metaspaceConstant.asResolvedJavaType() != null) {
                HotSpotResolvedObjectType type = metaspaceConstant.asResolvedJavaType();
                methodInfo.addDependentKlassData(binaryContainer, type);
                targetSymbol = AOTCompiledClass.metadataName(type);
                gotName = ((action == HotSpotConstantLoadAction.INITIALIZE) ? "got.init." : "got.") + targetSymbol;
            } else if (metaspaceConstant.asResolvedJavaMethod() != null && action == HotSpotConstantLoadAction.LOAD_COUNTERS) {
                targetSymbol = "counters." + JavaMethodInfo.uniqueMethodName(metaspaceConstant.asResolvedJavaMethod());
                gotName = "got." + targetSymbol;
                binaryContainer.addCountersSymbol(targetSymbol);
            }
        } else if (constant instanceof HotSpotObjectConstant) {
            HotSpotObjectConstant oopConstant = (HotSpotObjectConstant) constant;
            if (oopConstant instanceof HotSpotConstantPoolObject) {
                HotSpotConstantPoolObject cpo = (HotSpotConstantPoolObject) oopConstant;
                // Even if two locations use the same object, resolve separately
                targetSymbol = "ldc." + cpo.getCpType().getName() + cpo.getCpi();
            } else {
                // String constant.
                targetSymbol = "ldc." + oopConstant.toValueString();
            }
            Integer offset = binaryContainer.addOopSymbol(targetSymbol);
            gotName = "got.ldc." + offset;
        } else if (constant instanceof HotSpotSentinelConstant) {
            targetSymbol = "state.M" + methodInfo.getCodeId();
            gotName = "got." + targetSymbol;
        }

        assert gotName != null : "Unknown constant type: " + constant;

        InstructionDecoder decoder = InstructionDecoder.getInstructionDecoder(target);
        decoder.decodePosition(methodInfo.getCompilationResult().getTargetCode(), dataPatch.pcOffset);
        int instructionEndOffset = decoder.currentEndOfInstruction();

        int textBaseOffset = methodInfo.getTextSectionOffset();
        int relocOffset = textBaseOffset + instructionEndOffset;

        Symbol relocationSymbol = binaryContainer.getSymbol(gotName);
        assert relocationSymbol != null : "symbol for " + gotName + " missing";
        Relocation reloc = new Relocation(relocOffset, RelocType.METASPACE_GOT_REFERENCE, 0, binaryContainer.getCodeContainer(), relocationSymbol);
        binaryContainer.addRelocation(reloc);
    }

    private void processDataSectionReference(DataPatch dataPatch, CompiledMethodInfo methodInfo) {
        DataSectionReference dataReference = (DataSectionReference) dataPatch.reference;

        InstructionDecoder decoder = InstructionDecoder.getInstructionDecoder(target);
        decoder.decodePosition(methodInfo.getCompilationResult().getTargetCode(), dataPatch.pcOffset);
        int instructionEndOffset = decoder.currentEndOfInstruction();

        int textBaseOffset = methodInfo.getTextSectionOffset();
        int relocOffset = textBaseOffset + instructionEndOffset;
        int dataOffset = dataReference.getOffset();

        DataSection dataSection = methodInfo.getCompilationResult().getDataSection();
        DataSection.Data data = dataSection.findData(dataReference);
        int size = data.getSize();
        int alignment = data.getAlignment();
        byte[] value = new byte[size];
        ByteBuffer buffer = ByteBuffer.wrap(value).order(ByteOrder.nativeOrder());
        DataSection.emit(buffer, data, (p, c) -> {
        });
        String targetSymbol = "data.M" + methodInfo.getCodeId() + "." + dataOffset;
        Symbol relocationSymbol = binaryContainer.getSymbol(targetSymbol);
        if (relocationSymbol == null) {
            int symSize = Math.max(8, size);
            int symAlig = Math.max(8, alignment);
            int offsetInConstantDataSection = binaryContainer.addConstantData(value, symAlig);
            relocationSymbol = binaryContainer.getConstantDataContainer().createSymbol(offsetInConstantDataSection, Kind.OBJECT, Binding.LOCAL, symSize, targetSymbol);
        }
        Relocation reloc = new Relocation(relocOffset, RelocType.METASPACE_GOT_REFERENCE, 0, binaryContainer.getCodeContainer(), relocationSymbol);
        binaryContainer.addRelocation(reloc);
    }

}
