Can llvm lli excute swift ir

断了今生、忘了曾经 提交于 2020-01-14 02:58:07

问题


I have a function (written in Swift) and I would like to get the LLVM IR for the function PLUS any dependencies so that I can run the resulting LLVM IR in a fully self-contained environment.

As an example, consider the following function:

func plus(a: Int, b: Int) ->Int {
    return a + b
}

plus(5, 7)

I can pass the emit-ir option to swiftc, however, the resulting LLVM IR contains external calls and the resulting IR cannot be run using lli (the error is shown below).

LLVM ERROR: Program used external function '__TFSsa6C_ARGVGVSs20UnsafeMutablePointerGS_VSs4Int8__' which could not be resolved!

Is there any way of grabbing the IR for these external functions so that I can use lli to run the program?


回答1:


You need to teach the lli about dependencies of the binary. Here is how to do so.

Let's say there is a "hello world" program:

// main.swift
print("hello")

Compile it to LLVM Bitcode and to a normal executable:

> swiftc main.swift -o hello
> swiftc -emit-bc main.swift -o hello.bc

If you run the main.bc via lli as is, then you will have a similar error to the one you saw with your program.

To learn about dependencies you can use otool on macOS and ldd on Linux:

> otool -L /path/to/executbale
> ldd /path/to/executbale

Here are dependencies for the "hello world" program:

> otool -L ./hello
./hello:
    /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation (compatibility version 150.0.0, current version 1450.15.0)
    /usr/lib/libobjc.A.dylib (compatibility version 1.0.0, current version 228.0.0)
    /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1252.0.0)
    @rpath/libswiftCore.dylib (compatibility version 1.0.0, current version 900.0.74)
    @rpath/libswiftSwiftOnoneSupport.dylib (compatibility version 1.0.0, current version 900.0.74)

In this case, we need to pass libswiftSwiftOnoneSupport.dylib and libswiftCore.dylib to lli sing -load option.

On my machine these libraries live in this directory (I used find to find them):

/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx

Finally, here is how you can run your program:

> lli \
    -load=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/libswiftCore.dylib \
    -load=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/libswiftSwiftOnoneSupport.dylib \
    hello.bc

Also, note the order of arguments: it is important that the bitcode file goes last.



来源:https://stackoverflow.com/questions/48293032/can-llvm-lli-excute-swift-ir

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!