使用 LLVM 链接器生成 C 代码

Using the LLVM linker to produce C code

我尝试使用以下命令从 llvm-g++ 编译的 C++ 代码生成 C 代码:

llvm-g++ -emit-llvm -c ./example.cpp -o example.o
llc -march=c example.o

我在一台机器上试过这些命令 运行 Ubuntu (Linux 3.16.0-45-generic).

然而,LLVM 静态链接器没有将 C 代码写入标准输出,而是报告编译文件无效:error: expected top-level entity.

如何使用 LLVM 链接器生成 C 代码?

如手册页所述:

The llc command compiles LLVM source inputs
into assembly language for a specified architecture.

它不会对目标文件进行逆向工程以生成 C 文件(这就是您要实现的目标),这对我来说意义不大。

要了解支持哪些架构(大致意思是 CPU),您可以使用:

 llc -version

(您会注意到 'C' 不是架构)。

如果您尝试将一段 C++ 代码重写为 C,最好的办法是手动完成。您需要在 C 中重写所有特定于 C++ 的内容(类、异常、模板等),这将花费或多或少的时间,具体取决于您的 C++ 代码的复杂性。

不幸的是,在 Ubuntu 系统上发出 LLVM 位码可能会有点痛苦,因为它们将 DragonEgg 作为默认前端提供 - 请参阅 this question and this bugreport

如果您对上面生成的文件执行 file example.o,您会发现它实际上不是 LLVM IR 位码(这解释了错误):

$ file example.o
example.o: ELF 64-bit LSB  relocatable, x86-64, version 1 (SYSV), not stripped

在 Ubuntu 系统上获取 LLVM IR 位码的最简单方法是使用 clang:

$ clang -emit-llvm -c example.cpp -o example.o
$ file example.o
example.o: LLVM IR bitcode

也就是说,C 后端已在 LLVM 3.1 中删除(参见 release notes and this question)。正如您从 llc -version 的输出中看到的那样,它没有被列出并且尝试使用它会在我的 Ubuntu 14.04 系统上出现以下错误:

llc-3.4: error: invalid target 'c'.

原来的 C 后端 (llvm-cbe) 在 3.1 中被删除 (release notes), but there is this Julia project, resurrected LLVM "C Backend", with improvements,它复活了。