前言
本章對(duì)應(yīng)官方教程第8章。本章介紹如何將語言編譯為目標(biāo)文件。
教程如下:
開始
因?yàn)槲覀冎坝昧?code>JIT,但是我們現(xiàn)在也要生成目標(biāo)文件,兩者只能選其一,所以我們現(xiàn)在把封裝一下JIT以及main文件。
首先是封裝JIT,我這里封裝為類CodeRunner。
class CodeRunner {
private let jit: JIT
private typealias fnPr = @convention(c) () -> Double
init(machine: TargetMachine) {
jit = JIT(machine: machine)
}
public func run(module: Module) {
do {
let handle = try jit.addEagerlyCompiledIR(module, { (_) -> JIT.TargetAddress in
return JIT.TargetAddress()
})
let addr = try jit.address(of: "__anon_expr")
let fn = unsafeBitCast(addr, to: fnPr.self)
print("\(fn())")
try jit.removeModule(handle)
} catch {
fatalError("Adds the IR from a given module failure.")
}
}
}
接著是main文件。
let isUseJIT = false
func readFile(_ path: String) -> String? {
var path = path
if path.hasSuffix("\n") {
path.removeLast()
}
guard path.split(separator: ".").last! == "k" else {
print("Expected file is *.k.")
return nil
}
do {
return try String(contentsOfFile: path, encoding: .utf8)
} catch {
print("Read file \(path) failure.")
return nil
}
}
func main() {
//初始化Module和中間代碼優(yōu)化器
initModule()
//解析器
let parser = Parser()
if let path = String(data: FileHandle.standardInput.availableData, encoding: .utf8) {
if let str = readFile(path) {
parser.parse(str)
//指定目標(biāo)
theModule.targetTriple = .default
do {
//這個(gè)初始化方法里已經(jīng)調(diào)用了initializeLLVM()
let targetMachine = try TargetMachine(triple: .default,
cpu: "x86-64",
features: "",
optLevel: .default,
relocations: .default,
codeModel: .default)
//指定數(shù)據(jù)布局
theModule.dataLayout = targetMachine.dataLayout
//把代碼優(yōu)化放在這里
let pass = PassPipeliner(module: theModule)
pass.execute()
if isUseJIT {
let runner = CodeRunner(machine: targetMachine)
runner.run(module: theModule)
} else {
//修改為自己的路徑
let path = "填你自己的路徑"
//這里就是生成目標(biāo)文件
try targetMachine.emitToFile(module: theModule, type: .object, path: path)
print("Wrote \(path)")
}
} catch {
print("\(error)")
}
}
}
}
main()
測試
我們新建.k文件average.k。
def average(x y) (x + y) * 0.5;
我們運(yùn)行代碼生成目標(biāo)文件output.o,我們可以用下面命令看一下目標(biāo)文件是否生成了符號(hào)表。
objdump -t output.o
會(huì)輸出類似的以下信息。
output.o: file format Mach-O 64-bit x86-64
SYMBOL TABLE:
0000000000000000 g F __TEXT,__text _average
生成完目標(biāo)文件我們需要寫一段C++代碼進(jìn)行調(diào)用。
#include <iostream>
extern "C" {
double average(double, double);
}
int main() {
std::cout << "average of 3.0 and 4.0: " << average(3.0, 4.0) << std::endl;
}
將程序鏈接到output.o并查看結(jié)果
clang++ main.cpp output.o -o main
./main
//輸出
average of 3.0 and 4.0: 3.5
完整代碼請參考倉庫。
可能遇到的問題
macOS下'wchar.h' File Not Found
參考回答macOS 'wchar.h' File Not Found
open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg
Mojava下安裝頭文件包即可。