Transform/Compile to C/CPP as a target

Sebastien Alaiwan via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Jul 28 10:28:55 PDT 2016


On Monday, 25 July 2016 at 07:53:17 UTC, Stefan Koch wrote:
> On Saturday, 23 July 2016 at 12:27:24 UTC, ParticlePeter wrote:
>> Is there any kind of project or workflow that converts D 
>> (subset) to C/CPP ?
>
> The short answer is no, not for any recent version of D.

The long answer is it's kind of possible, but the resulting C 
code is not human-readable.
I just managed today to achieve some transformation to C with the 
below script:

# compile the D modules to llvm bitcode
$ ldc2 hello.d -c -output-ll -ofhello.ll
$ ldc2 lib.d -c -output-ll -oflib.ll

# merge them into one LLVM bitcode module
$ llvm-link-3.8 hello.ll lib.ll -o full.bc
$ llvm-dis-3.8 full.bc -o=full.ll

# convert bitcode to C
$ llvm-cbe full.ll

# patch the generated C, so it's compilable
$ sed -i "s/.*APInt.*//" full.cbe.c
$ sed -i "s/^uint32_t main(uint32_t llvm_cbe_argc_arg, 
uint8_t\*\* llvm_cbe_argv_arg)/int main(int llvm_cbe_argc_arg, 
char** llvm_cbe_argv_arg)/" full.cbe.c
$ sed -i "s/^uint32_t main(uint32_t, uint8_t\*\*)/int main(int, 
char**)/" full.cbe.c

# compile the C program and run it.
$ gcc -w full.cbe.c -o full.exe -lphobos2
$ ./full.exe
Hello, world: 46

I only tried this with a very minimalistic subset of D at the 
moment.
Most of the magic occurs in the "llvm-cbe" program, which is a 
"resurrected LLVM C backend" ( 
https://github.com/JuliaComputing/llvm-cbe ).






More information about the Digitalmars-d-learn mailing list