Skip to content

Consistent AccessViolationException when calling BuildCall2 #227

Closed
@DuncanMcPherson

Description

@DuncanMcPherson

I have a project that is using LLVM and I am trying to write my own implementation of the C Standard library's strlen. I got what I though would be a valid declaration:

private void DeclareStrLen()
{
    var strlenType = LLVMTypeRef.CreateFunction(LLVMTypeRef.Int32,
        new[] { LLVMTypeRef.CreatePointer(LLVMTypeRef.Int8, 0) }, false);
    var strlenFunction = _module.GetNamedFunction("strlen");
    if (strlenFunction.Handle != IntPtr.Zero)
    {
        return;
    }

    strlenFunction = _module.AddFunction("strlen", strlenType);

    var entry = strlenFunction.AppendBasicBlock("entry");
    _builder.PositionAtEnd(entry);

    var str = strlenFunction.GetParam(0);

    var length = _builder.BuildAlloca(LLVMTypeRef.Int32, "length");
    _builder.BuildStore(LLVMValueRef.CreateConstInt(LLVMTypeRef.Int32, 0, false), length);

    var loopCond = strlenFunction.AppendBasicBlock("loopCond");
    var loopBody = strlenFunction.AppendBasicBlock("loopBody");
    var loopEnd = strlenFunction.AppendBasicBlock("loopEnd");

    _builder.BuildBr(loopCond);

    _builder.PositionAtEnd(loopCond);
    var currentIndex = _builder.BuildLoad2(LLVMTypeRef.Int32, length, "currentIndex");
    var currentCharPtr = _builder.BuildInBoundsGEP2(LLVMTypeRef.Int8, str, new LLVMValueRef[] { currentIndex });
    var currentChar = _builder.BuildLoad2(LLVMTypeRef.Int8, currentCharPtr, "currentChar");
    var isNullChar = _builder.BuildICmp(LLVMIntPredicate.LLVMIntEQ, currentChar,
        LLVMValueRef.CreateConstInt(LLVMTypeRef.Int8, 0, false), "isNullChar");

    _builder.BuildCondBr(isNullChar, loopEnd, loopBody);

    _builder.PositionAtEnd(loopBody);
    var newIndex = _builder.BuildAdd(currentIndex, LLVMValueRef.CreateConstInt(LLVMTypeRef.Int32, 1, false),
        "newIndex");
    _builder.BuildStore(newIndex, length);
    _builder.BuildBr(loopCond);

    _builder.PositionAtEnd(loopEnd);
    var finalLength = _builder.BuildLoad2(LLVMTypeRef.Int32, length, "finalLength");
    _builder.BuildRet(finalLength);
}

However, when I tried to do something like var length = _builder.BuildCall2(_module.GetNamedFunction("strlen").TypeOf, _module.GetNamedFunction("strlen"), [/*valueRef here*/]);
I always got an AccessViolationException.
At first, I thought it was an issue with my code, but after 2-3 hours of debugging and conferring with peers, no answers could be found. Please help

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions