Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the LLVM linker to produce C code

Tags:

c++

c

linker

llvm

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?

like image 260
edition Avatar asked Aug 12 '15 08:08

edition


Video Answer


2 Answers

The original C backend (llvm-cbe) was removed in 3.1 (release notes), but there is this Julia project, resurrected LLVM "C Backend", with improvements, which resurrected it.

like image 198
Albert Avatar answered Sep 22 '22 01:09

Albert


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'.
like image 41
mjturner Avatar answered Sep 22 '22 01:09

mjturner