问题
I have tried to generate C code from C++ code compiled by llvm-g++, using the following commands:
llvm-g++ -emit-llvm -c ./example.cpp -o example.o
llc -march=c example.o
I tried these commands on a machine running Ubuntu (Linux 3.16.0-45-generic).
However instead of writing C code to standard output, the LLVM static linker reports that the compiled file is invalid: error: expected top-level entity.
How can I generate C code using the LLVM linker?
回答1:
Unfortunately emitting LLVM bitcode on Ubuntu systems can be a bit painful because they ship DragonEgg as the default frontend - see this question and this bugreport.
If you do a file example.o on the file you generated above, you'll see that it's not actually LLVM IR bitcode (which explains the error):
$ file example.o
example.o: ELF 64-bit LSB relocatable, x86-64, version 1 (SYSV), not stripped
The easiest way to get LLVM IR bitcode on an Ubuntu system is to use clang:
$ clang -emit-llvm -c example.cpp -o example.o
$ file example.o
example.o: LLVM IR bitcode
That said, the C backend was removed in LLVM 3.1 (see the release notes and this question). As you can see from the output of llc -version it's not listed and trying to use it gives the following error on my Ubuntu 14.04 system:
llc-3.4: error: invalid target 'c'.
回答2:
As the manual page says:
The llc command compiles LLVM source inputs
into assembly language for a specified architecture.
It does not reverse-engineer an object file to produce a C file (that is what you are trying to achieve) which is something that makes little sense to me.
To know which architecture are supported (roughly meaning which CPU) you can use:
llc -version
(you'll notice that 'C' is not an architecture).
If you are trying to rewrite a piece of C++ code as C, your best bet is to just do it manually. You'll need to rewrite all the C++ specific things (classes, exceptions, templates, ...) in C which is something that will take a more or less time depending on the complexity of your C++ code.
回答3:
The original C backend (llvm-cbe) was removed in 3.1 (release notes), but there is this Jula project, resurrected LLVM "C Backend", with improvements, which resurrected it.
来源:https://stackoverflow.com/questions/31960290/using-the-llvm-linker-to-produce-c-code