ronantakizawa/codereview-bench huggingface dataset:
Repository: dotnet/runtime
File: src/coreclr/jit/emitwasm.cpp (C++)

Code before:
}

size_t emitter::emitEncodeLEB64(uint8_t* destination, const void* source, bool valueIsSigned)
{
    assert(source);

    unsigned char b;
    unsigned char * originalDestination = destination;
    if (valueIsSigned) {
        int64_t value = *((int64_t*)source);
        int more = 1, signBit;

        while (more) {
            b = (unsigned char)(value & 0x7FL);
            value >>= 7;

            signBit = (b & 0x40u) != 0;
            if (
                ((value == 0) && !signBit) ||
                ((value == -1) && signBit)
            )
                more = 0;
            else
                b |= 0x80;

            if (originalDestination)
                *destination = b;
            destination++;
        }
    } else {
        uint64_t value = *((uint64_t*)source);

        do {
            b = (unsigned char)(value & 0x7Ful);
            value >>= 7;

            if (value != 0)
                b |= 0x80;

            if (originalDestination)
                *destination = b;
            destination++;
        } while (value != 0);
    }

    return (size_t)(destination - originalDestination);
}

emitter::insFormat emitter::emitInsFormat(instruction ins)
{
    // clang-format off

Review comment (bug):
```suggestion
            if (originalDestination != nullptr)
```

Code after:
    const static insFormat insFormats[] =
    {
        #define INST(id, nm, info, fmt, opcode) fmt,
        #include "instrs.h"
    };
    // clang-format on

    assert(ins < ArrLen(insFormats));
    assert((insFormats[ins] != IF_NONE));
    return insFormats[ins];
}

static unsigned GetInsOpcode(instruction ins)
{
    assert(ins < ArrLen(insOpcodes));
    return insOpcodes[ins];
}

size_t emitter::emitSizeOfInsDsc(instrDesc* id) const
{
    if (emitIsSmallInsDsc(id))
        return SMALL_IDSC_SIZE;

    if (id->idIsLargeCns())
    {
        assert(!id->idIsLargeDsp());
        assert(!id->idIsLargeCall());
        return sizeof(instrDescCns);
    }
    return sizeof(instrDesc);
}

unsigned emitter::emitGetAlignHintLog2(const instrDesc* id)
{
    // FIXME
    return 0;
}

unsigned emitter::SizeOfULEB128(uint64_t value)
{
    // bits_to_encode = (data != 0) ? 64 - CLZ(x) : 1 = 64 - CLZ(data | 1)
    // bytes = ceil(bits_to_encode / 7.0);            = (6 + bits_to_encode) / 7
    unsigned x = 6 + 64 - (unsigned)BitOperations::LeadingZeroCount(value | 1UL);
    // Division by 7 is done by (x * 37) >> 8 where 37 = ceil(256 / 7).
    // This works for 0 <= x < 256 / (7 * 37 - 256), i.e. 0 <= x <= 85.
    return (x * 37) >> 8;
}

unsigned emitter::SizeOfSLEB128(int64_t value)
{
    // The same as SizeOfULEB128 calculation but we have to account for the sign bit.
Repository: dotnet/runtime
File: src/coreclr/jit/emitwasm.cpp (C++)

Code before:
            value >>= 7;

            signBit = (b & 0x40u) != 0;
            if (
                ((value == 0) && !signBit) ||
                ((value == -1) && signBit)
            )
                more = 0;
            else
                b |= 0x80;

            if (originalDestination)
                *destination = b;
            destination++;
        }
    } else {
        uint64_t value = *((uint64_t*)source);

        do {
            b = (unsigned char)(value & 0x7Ful);
            value >>= 7;

            if (value != 0)
                b |= 0x80;

            if (originalDestination)
                *destination = b;
            destination++;
        } while (value != 0);
    }

    return (size_t)(destination - originalDestination);
}

emitter::insFormat emitter::emitInsFormat(instruction ins)
{
    // clang-format off
    const static insFormat insFormats[] =
    {
        #define INST(id, nm, info, fmt, opcode) fmt,
        #include "instrs.h"
    };
    // clang-format on

    assert(ins < ArrLen(insFormats));
    assert((insFormats[ins] != IF_NONE));
    return insFormats[ins];
}

static unsigned GetInsOpcode(instruction ins)
{

Review comment (bug):
```suggestion
            if (originalDestination != nullptr)
```

Code after:
    assert(ins < ArrLen(insOpcodes));
    return insOpcodes[ins];
}

size_t emitter::emitSizeOfInsDsc(instrDesc* id) const
{
    if (emitIsSmallInsDsc(id))
        return SMALL_IDSC_SIZE;

    if (id->idIsLargeCns())
    {
        assert(!id->idIsLargeDsp());
        assert(!id->idIsLargeCall());
        return sizeof(instrDescCns);
    }
    return sizeof(instrDesc);
}

unsigned emitter::emitGetAlignHintLog2(const instrDesc* id)
{
    // FIXME
    return 0;
}

unsigned emitter::SizeOfULEB128(uint64_t value)
{
    // bits_to_encode = (data != 0) ? 64 - CLZ(x) : 1 = 64 - CLZ(data | 1)
    // bytes = ceil(bits_to_encode / 7.0);            = (6 + bits_to_encode) / 7
    unsigned x = 6 + 64 - (unsigned)BitOperations::LeadingZeroCount(value | 1UL);
    // Division by 7 is done by (x * 37) >> 8 where 37 = ceil(256 / 7).
    // This works for 0 <= x < 256 / (7 * 37 - 256), i.e. 0 <= x <= 85.
    return (x * 37) >> 8;
}

unsigned emitter::SizeOfSLEB128(int64_t value)
{
    // The same as SizeOfULEB128 calculation but we have to account for the sign bit.
    unsigned x = 1 + 6 + 64 - (unsigned)BitOperations::LeadingZeroCount((uint64_t)(value ^ (value >> 63)) | 1UL);
    return (x * 37) >> 8;
}

unsigned emitter::instrDesc::idCodeSize() const
{
#ifdef TARGET_WASM32
    static const unsigned PADDED_RELOC_SIZE = 5;
#else
#error WASM64
#endif

    // Currently, all our instructions have 1 byte opcode.
    unsigned size = 1;
Repository: dotnet/runtime
File: src/coreclr/jit/emitwasm.cpp (C++)

Code before:
{
    NYI_WASM("emitIns_R_F");
}

void emitter::emitIns_Mov(instruction ins, emitAttr attr, regNumber dstReg, regNumber srcReg, bool canSkip)
{
    NYI_WASM("emitIns_Mov");
}

void emitter::emitIns_R_R(instruction ins, emitAttr attr, regNumber reg1, regNumber reg2)
{
    NYI_WASM("emitIns_R_R");
}

void emitter::emitIns_S_R(instruction ins, emitAttr attr, regNumber ireg, int varx, int offs)
{
    NYI_WASM("emitIns_S_R");
}

bool emitter::emitInsIsStore(instruction ins)
{
    NYI_WASM("emitInsIsStore");
    return false;
}

size_t emitter::emitEncodeLEB64(uint8_t* destination, const void* source, bool valueIsSigned)
{
    assert(source);

    unsigned char b;
    unsigned char * originalDestination = destination;
    if (valueIsSigned) {
        int64_t value = *((int64_t*)source);
        int more = 1, signBit;

        while (more) {
            b = (unsigned char)(value & 0x7FL);
            value >>= 7;

            signBit = (b & 0x40u) != 0;
            if (
                ((value == 0) && !signBit) ||
                ((value == -1) && signBit)
            )
                more = 0;
            else
                b |= 0x80;

            if (originalDestination)
                *destination = b;
            destination++;

Review comment (bug):
Header comment? In particular if `destination` can be nullptr.

There is already a ULEB128 size estimator, and we need one for LEB128. Would you suggest calling this with `nullptr` to get the size, then calling it again later to fill in the contents? 

Or should we create a separate size estimator for LEB128 and just have this assert it has a non-null destination?

Code after:
{
    NYI_WASM("emitIns_Mov");
}

void emitter::emitIns_R_R(instruction ins, emitAttr attr, regNumber reg1, regNumber reg2)
{
    NYI_WASM("emitIns_R_R");
}

void emitter::emitIns_S_R(instruction ins, emitAttr attr, regNumber ireg, int varx, int offs)
{
    NYI_WASM("emitIns_S_R");
}

bool emitter::emitInsIsStore(instruction ins)
{
    NYI_WASM("emitInsIsStore");
    return false;
}

emitter::insFormat emitter::emitInsFormat(instruction ins)
{
    // clang-format off
    const static insFormat insFormats[] =
    {
        #define INST(id, nm, info, fmt, opcode) fmt,
        #include "instrs.h"
    };
    // clang-format on

    assert(ins < ArrLen(insFormats));
    assert((insFormats[ins] != IF_NONE));
    return insFormats[ins];
}

static unsigned GetInsOpcode(instruction ins)
{
    assert(ins < ArrLen(insOpcodes));
    return insOpcodes[ins];
}

size_t emitter::emitSizeOfInsDsc(instrDesc* id) const
{
    if (emitIsSmallInsDsc(id))
        return SMALL_IDSC_SIZE;

    if (id->idIsLargeCns())
    {
        assert(!id->idIsLargeDsp());
        assert(!id->idIsLargeCall());
        return sizeof(instrDescCns);
Repository: dotnet/runtime
File: src/coreclr/jit/emitwasm.cpp (C++)

Code before:
        #define INST(id, nm, info, fmt, opcode) fmt,
        #include "instrs.h"
    };
    // clang-format on

    assert(ins < ArrLen(insFormats));
    assert((insFormats[ins] != IF_NONE));
    return insFormats[ins];
}

static unsigned GetInsOpcode(instruction ins)
{
    assert(ins < ArrLen(insOpcodes));
    return insOpcodes[ins];
}

size_t emitter::emitSizeOfInsDsc(instrDesc* id) const
{
    switch (id->idInsFmt())
    {
        case IF_I32:
        case IF_I64:
        case IF_F32:
        case IF_F64:
            return sizeof(instrDescWasmConstant);
    }

    if (emitIsSmallInsDsc(id))
        return SMALL_IDSC_SIZE;

    if (id->idIsLargeCns())
    {
        assert(!id->idIsLargeDsp());
        assert(!id->idIsLargeCall());
        return sizeof(instrDescCns);
    }
    return sizeof(instrDesc);
}

size_t SizeOfULEB128(uint64_t value)
{
    // Reuses the encoder for consistency and simplicity.
    // TODO: If this becomes a bottleneck, do a more direct size estimation.
    return EncodeLEB64(nullptr, &value, false);
}

size_t SizeOfLEB128(int64_t value)
{
    // Reuses the encoder for consistency and simplicity.
    // TODO: If this becomes a bottleneck, do a more direct size estimation.
    return EncodeLEB64(nullptr, &value, true);

Review comment (suggestion):
```suggestion
        default:
            break;
    }
```

Code after:
            break;
        case IF_MEMARG:
        {
            uint64_t align = emitGetAlignHintLog2(this);
            assert(align < 64); // spec says align > 2^6 produces a memidx for multiple memories.
            size += SizeOfULEB128(align);
            size += idIsCnsReloc() ? PADDED_RELOC_SIZE : SizeOfULEB128(emitGetInsSC(this));
            break;
        }
        default:
            unreached();
    }
    return size;
}

void emitter::emitSetShortJump(instrDescJmp* id)
{
    NYI_WASM("emitSetShortJump");
}

size_t emitter::emitOutputULEB128(uint8_t* destination, uint64_t value)
{
    uint8_t* buffer = destination + writeableOffset;
    if (value >= 0x80)
    {
        int pos = 0;
        do
        {
            buffer[pos++] = (uint8_t)((value & 0x7F) | ((value >= 0x80) ? 0x80u : 0));
            value >>= 7;
        } while (value > 0);

        return pos;
    }
    else
    {
        buffer[0] = (uint8_t)value;
        return 1;
    }
}

size_t emitter::emitOutputSLEB128(uint8_t* destination, int64_t value)
{
    uint8_t* buffer = destination + writeableOffset;
    bool     cont   = true;
    int      pos    = 0;
    while (cont)
    {
        uint8_t b = ((uint8_t)value & 0x7F);
        value >>= 7;
        bool isSignBitSet = (b & 0x40) != 0;
Repository: dotnet/runtime
File: src/coreclr/jit/emitwasm.cpp (C++)

Code before:

        pCodeRW = pCode + writeableOffset;
    }

    emitDispInsHex(id, pCodeRW, sz);

    printf("      ");

    instruction ins = id->idIns();
    insFormat   fmt = id->idInsFmt();

    emitDispInst(ins);

    // The reference for the following style of display is wasm-objdump output.
    //
    switch (fmt)
    {
        case IF_OPCODE:
        case IF_BLOCK:
            break;

        case IF_LABEL:
        case IF_ULEB128:
        {
            cnsval_ssize_t imm = emitGetInsSC(id);
            printf(" %llu", imm);
        }
        break;

        case IF_SLEB128:
        {
            cnsval_ssize_t imm = emitGetInsSC(id);
            printf(" %lli", imm);
        }
        break;

        case IF_F32:
        case IF_F64:
        {
            cnsval_ssize_t bits = emitGetInsSC(id);
            double         value;
            memcpy(&value, &bits, sizeof(double));
            printf(" %f", value);
        }
        break;

        case IF_MEMARG:
        {
            // TODO-WASM: decide what our strategy for alignment hints is and display these accordingly.
            unsigned       log2align = 1;
            cnsval_ssize_t offset    = emitGetInsSC(id);

Review comment (bug):
Using `%llu` (unsigned) format specifier with a signed `cnsval_ssize_t` value may display negative values incorrectly. Since IF_ULEB128 is intended for unsigned values (branch targets, local indices), consider casting to `(uint64_t)` or use an appropriate unsigned format to avoid confusion in debug output.

Code after:
    BYTE* pCodeRW = nullptr;
    if (pCode != nullptr)
    {
        /* Display the instruction hex code */
        assert(((pCode >= emitCodeBlock) && (pCode < emitCodeBlock + emitTotalHotCodeSize)) ||
               ((pCode >= emitColdCodeBlock) && (pCode < emitColdCodeBlock + emitTotalColdCodeSize)));

        pCodeRW = pCode + writeableOffset;
    }

    emitDispInsHex(id, pCodeRW, sz);

    printf("      ");

    instruction ins = id->idIns();
    insFormat   fmt = id->idInsFmt();

    emitDispInst(ins);

    // The reference for the following style of display is wasm-objdump output.
    //
    switch (fmt)
    {
        case IF_OPCODE:
        case IF_BLOCK:
            break;

        case IF_LABEL:
        case IF_ULEB128:
        {
            cnsval_ssize_t imm = emitGetInsSC(id);
            printf(" %llu", (uint64_t)imm);
        }
        break;

        case IF_SLEB128:
        {
            cnsval_ssize_t imm = emitGetInsSC(id);
            printf(" %lli", (int64_t)imm);
        }
        break;

        case IF_F32:
        case IF_F64:
        {
            cnsval_ssize_t bits = emitGetInsSC(id);
            double         value;
            memcpy(&value, &bits, sizeof(double));
            printf(" %f", value);
        }
        break;
Repository: dotnet/runtime
File: src/coreclr/jit/emitwasm.cpp (C++)

Code before:
        }
        break;

        case IF_SLEB128:
        {
            cnsval_ssize_t imm = emitGetInsSC(id);
            printf(" %lli", imm);
        }
        break;

        case IF_F32:
        case IF_F64:
        {
            cnsval_ssize_t bits = emitGetInsSC(id);
            double         value;
            memcpy(&value, &bits, sizeof(double));
            printf(" %f", value);
        }
        break;

        case IF_MEMARG:
        {
            // TODO-WASM: decide what our strategy for alignment hints is and display these accordingly.
            unsigned       log2align = 1;
            cnsval_ssize_t offset    = emitGetInsSC(id);
            printf(" %u %llu", log2align, offset);
        }
        break;

        default:
            unreached();
    }

    printf("\n");
}

//--------------------------------------------------------------------
// emitDispInst: Display the instruction name.
//
void emitter::emitDispInst(instruction ins)
{
    const char* instName = codeGen->genInsName(ins);
    printf("%s", instName);
}

//--------------------------------------------------------------------
// emitDispInsHex: Display (optionally) the instruction encoding in hex.
//
void emitter::emitDispInsHex(instrDesc* id, BYTE* code, size_t sz)
{
    if (!emitComp->opts.disCodeBytes)

Review comment (bug):
Using `%llu` (unsigned) format specifier with a signed `cnsval_ssize_t` value may display negative values incorrectly. For IF_MEMARG offsets which should be unsigned, consider casting to `(uint64_t)` to ensure correct display in debug output.
```suggestion
            printf(" %u %llu", log2align, (uint64_t)offset);
```

Code after:

        case IF_LABEL:
        case IF_ULEB128:
        {
            cnsval_ssize_t imm = emitGetInsSC(id);
            printf(" %llu", (uint64_t)imm);
        }
        break;

        case IF_SLEB128:
        {
            cnsval_ssize_t imm = emitGetInsSC(id);
            printf(" %lli", (int64_t)imm);
        }
        break;

        case IF_F32:
        case IF_F64:
        {
            cnsval_ssize_t bits = emitGetInsSC(id);
            double         value;
            memcpy(&value, &bits, sizeof(double));
            printf(" %f", value);
        }
        break;

        case IF_MEMARG:
        {
            // TODO-WASM: decide what our strategy for alignment hints is and display these accordingly.
            unsigned       log2align = emitGetAlignHintLog2(id) + 1;
            cnsval_ssize_t offset    = emitGetInsSC(id);
            printf(" %u %llu", log2align, (uint64_t)offset);
        }
        break;

        default:
            unreached();
    }

    printf("\n");
}

//--------------------------------------------------------------------
// emitDispInst: Display the instruction name.
//
void emitter::emitDispInst(instruction ins)
{
    const char* instName = codeGen->genInsName(ins);
    printf("%s", instName);
}
Repository: dotnet/runtime
File: src/tests/Interop/common/ComActivationHelpers.cs (C#)

Code before:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Runtime.InteropServices;

public static class ComActivationHelpers
{
    public static IDisposable RegisterTypeForActivation<T>()
        where T: new()
    {
        Factory factory = new(() => new T());
        CoRegisterClassObject(
            typeof(T).GUID,
            factory,
            1, // CLSCTX_INPROC_SERVER
            2, // REGCLS_MULTIPLEUSE
            out uint cookie);
        return new RegistrationToken(cookie);
    }

    private class RegistrationToken(uint token) : IDisposable
    {
        public void Dispose()
        {
            CoRevokeClassObject(token);
        }
    }

    [DllImport("ole32")]
    private static extern int CoRegisterClassObject(
        in Guid rclsid,
        [MarshalAs(UnmanagedType.Interface)] IClassFactory pUnk,
        uint dwClsContext,
        uint flags,
        out uint lpdwRegister);

    [DllImport("ole32")]
    private static extern int CoRevokeClassObject(uint dwRegister);

    [ComImport]
    [ComVisible(false)]

Review comment (suggestion):
```suggestion
            1, // REGCLS_MULTIPLEUSE
```

Code after:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Runtime.InteropServices;

public static class ComActivationHelpers
{
    public static IDisposable RegisterTypeForActivation<T>()
        where T: new()
    {
        Factory factory = new(() => new T());
        CoRegisterClassObject(
            typeof(T).GUID,
            factory,
            1, // CLSCTX_INPROC_SERVER
            1, // REGCLS_MULTIPLEUSE
            out uint cookie);
        return new RegistrationToken(cookie);
    }

    private class RegistrationToken(uint token) : IDisposable
    {
        public void Dispose()
        {
            CoRevokeClassObject(token);
        }
    }

    [DllImport("ole32")]
    private static extern int CoRegisterClassObject(
        in Guid rclsid,
        [MarshalAs(UnmanagedType.Interface)] IClassFactory pUnk,
        uint dwClsContext,
        uint flags,
        out uint lpdwRegister);

    [DllImport("ole32")]
    private static extern int CoRevokeClassObject(uint dwRegister);

    [ComImport]
    [ComVisible(false)]
Repository: dotnet/runtime
File: src/coreclr/vm/eepolicy.cpp (C++)

Code before:
    PEXCEPTION_POINTERS m_pExceptionInfo;
    // MethodDescs of the stack frames, the TOS is at index 0
    CDynArray<MethodDesc*> m_frames;

    StackWalkAction LogCallstackForLogCallbackWorker(CrawlFrame *pCF)
    {
        WRAPPER_NO_CONTRACT;

        if (m_pExceptionInfo != NULL)
        {
            // Skip managed frames that are not part of the stack that caused the exception
            // (they are part of the stack that is unwinding the exception)
            if (GetRegdisplaySP(pCF->GetRegisterSet()) < GetSP(m_pExceptionInfo->ContextRecord))
            {
                return SWA_CONTINUE;
            }
        }

        MethodDesc** itemPtr = m_frames.Append();
        if (itemPtr == nullptr)
        {
            // Memory allocation failure
            return SWA_ABORT;
        }

        *itemPtr = pCF->GetFunction();;

        return SWA_CONTINUE;
    }

    void PrintFrame(int index, const WCHAR* pWordAt)
    {
        WRAPPER_NO_CONTRACT;

        SString str(pWordAt);

        MethodDesc* pMD = m_frames[index];
        TypeString::AppendMethodInternal(str, pMD, TypeString::FormatNamespace|TypeString::FormatFullInst|TypeString::FormatSignature);
        str.Append(W("\n"));

        PrintToStdErrW(str.GetUnicode());
    }

public:

    CallStackLogger(PEXCEPTION_POINTERS pExceptionInfo)
    {
        WRAPPER_NO_CONTRACT;

        m_pExceptionInfo = pExceptionInfo;
    }

Review comment (suggestion):
Double semicolon should be removed. This is a syntax error.
```suggestion
        *itemPtr = pCF->GetFunction();
```

Code after:
    PEXCEPTION_POINTERS m_pExceptionInfo;
    // MethodDescs of the stack frames, the TOS is at index 0
    CDynArray<MethodDesc*> m_frames;

    StackWalkAction LogCallstackForLogCallbackWorker(CrawlFrame *pCF)
    {
        WRAPPER_NO_CONTRACT;

        if (m_pExceptionInfo != NULL)
        {
            // Skip managed frames that are not part of the stack that caused the exception
            // (they are part of the stack that is unwinding the exception)
            if (GetRegdisplaySP(pCF->GetRegisterSet()) < GetSP(m_pExceptionInfo->ContextRecord))
            {
                return SWA_CONTINUE;
            }
        }

        MethodDesc** itemPtr = m_frames.Append();
        if (itemPtr == nullptr)
        {
            // Memory allocation failure
            return SWA_ABORT;
        }

        *itemPtr = pCF->GetFunction();

        return SWA_CONTINUE;
    }

    void PrintFrame(int index, const WCHAR* pWordAt)
    {
        WRAPPER_NO_CONTRACT;

        SString str(pWordAt);

        MethodDesc* pMD = m_frames[index];
        TypeString::AppendMethodInternal(str, pMD, TypeString::FormatNamespace|TypeString::FormatFullInst|TypeString::FormatSignature);
        str.Append(W("\n"));

        PrintToStdErrW(str.GetUnicode());
    }

public:

    CallStackLogger(PEXCEPTION_POINTERS pExceptionInfo)
    {
        WRAPPER_NO_CONTRACT;

        m_pExceptionInfo = pExceptionInfo;
    }