5 ms·
for non compiler experts, how does llvm decouple a language from a target machine?
by poseid 10y ago
for non compiler experts, how does llvm decouple a language from a target machine?
- exDM69 10y agoLLVM specifies another "language", the LLVM intermediate representation (IR) which is easy to generate by a compiler frontend and suitable for running optimizations in, and then compile on to the target architecture. It's a bit like an assembly language with infinite registers and explicit control flow. E.g. Clang front end reads C code and emits LLVM IR. The LLVM backend (llvm-as) then reads the IR and generates target machine code.
- DannyBee 10y agoIt's important to note, however, that while LLVM IR is language and target independent, a lot of languages themselves are not target independent. IE LLVM does not make C magically portable, because C requires and creates target-specific information (for example sizeof). To give a simple example, you can't take: int *foo; printf("%d\n", sizeof(foo)) Compile it on a 16 bit platform to llvm bitcode and then run compile/run the llvm bitcode on a 64 bit platform, and get the right answer for that platform, and llvm can't solve this. The long story on this one is that it's basically not possible to even just move this stuff to dynamic evaluation in a frontend because you can depend on target specific things in the preprocessor, IIRC. Otherwise, you could, but it'd generate super-slow code unless you built llvm intrinsics for all these things, and then lowered them once you had target specific info. I believe TeNDRA and friends could do this at one point, but i might be misremembering (i've deliberately blocked most of my knowledge of ANDF)
- pcwalton 10y ago> The long story on this one is that it's basically not possible to even just move this stuff to dynamic evaluation in a frontend because you can depend on target specific things in the preprocessor, IIRC. Well, unless you go the whole way and interpret the language itself like CINT :)
- greenshackle2 10y agoJust so I understand, the problem is that compiling this code on a 16 bit vs 64 bit platform will produce different IR code? The IR code itself is "portable", but the C to IR compiler is using target specific information? (I've just been learning about assemblers and compilers, still trying to wrap my mind around this stuff. Would there be much educational value in writing IR code by hand?)
- pcwalton 10y ago> The IR code itself is "portable", but the C to IR compiler is using target specific information? Right. Consider how you'd compile something as simple as printf("%d", (int)sizeof(int));
- exDM69 10y agoThe point still stands, but I think sizeof(int*) or sizeof(int) is a poor example, because it could be compiled to a portable "getelementptr" LLVM instruction. However, Clang does not do this and emits a constant integer for sizeof() operations (according to my quick and dirty test).