Skip to content

Commit

Permalink
implement missing apis (#112)
Browse files Browse the repository at this point in the history
* implement missing apis

* follow guidelines for TryEmitToFile, EmitToFile

* call DisposeErrorMessage
  • Loading branch information
AviAvni authored and tannergooding committed Aug 19, 2019
1 parent 96cd847 commit f986236
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
10 changes: 10 additions & 0 deletions sources/LLVMSharp/Extensions/LLVMTargetRef.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,5 +69,15 @@ public string Name
public override int GetHashCode() => Pointer.GetHashCode();

public LLVMTargetRef GetNext() => LLVM.GetNextTarget(this);

public LLVMTargetMachineRef CreateTargetMachine(string triple, string cpu, string features, LLVMCodeGenOptLevel level, LLVMRelocMode reloc, LLVMCodeModel codeModel)
{
using (var marshaledTriple = new MarshaledString(triple))
using (var marshaledCPU = new MarshaledString(cpu))
using (var marshaledFeatures = new MarshaledString(features))
{
return LLVM.CreateTargetMachine(this, marshaledTriple, marshaledCPU, marshaledFeatures, level, reloc, codeModel);
}
}
}
}
45 changes: 45 additions & 0 deletions sources/LLVMSharp/Wrappers/LLVMTargetMachineRef.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Runtime.InteropServices;

namespace LLVMSharp
{
Expand All @@ -20,5 +21,49 @@ public static implicit operator LLVMTargetMachineRef(LLVMOpaqueTargetMachine* va
{
return (LLVMOpaqueTargetMachine*)value.Pointer;
}

public string CreateTargetDataLayout()
{
var pDataLayout = LLVM.CreateTargetDataLayout(this);

if (pDataLayout is null)
{
return string.Empty;
}

var span = new ReadOnlySpan<byte>(pDataLayout, int.MaxValue);
return span.Slice(0, span.IndexOf((byte)'\0')).AsString();
}

public bool TryEmitToFile(LLVMModuleRef module, string fileName, LLVMCodeGenFileType codegen, out string message)
{
using (var marshaledFileName = new MarshaledString(fileName))
{
sbyte* errorMessage;

int result = LLVM.TargetMachineEmitToFile(this, module, marshaledFileName, codegen, &errorMessage);

if (errorMessage is null)
{
message = string.Empty;
}
else
{
var span = new ReadOnlySpan<byte>(errorMessage, int.MaxValue);
message = span.Slice(0, span.IndexOf((byte)'\0')).AsString();
LLVM.DisposeErrorMessage(errorMessage);
}

return result == 0;
}
}

public void EmitToFile(LLVMModuleRef module, string fileName, LLVMCodeGenFileType codegen)
{
if (!TryEmitToFile(module, fileName, codegen, out string Error))
{
throw new ExternalException(Error);
}
}
}
}

0 comments on commit f986236

Please sign in to comment.