r/ProgrammingLanguages • • 4h ago

Discussion Compiling to C

Ive found a lot of languages on this sub compile to c code instead of assembly or a backend. I'm curious what the advantages / disadvantages are to this. I know c is pretty optimized so is this an easy way to make a performant language or does it just make it simpler. I dont know c but I know assembly and some QBE so what are the pros and cons to directly compiling to assembly ( is it just more flexibility? etc...)

0 Upvotes

20 comments sorted by

4

u/konacurrents 3h ago

C is the portable "assembly". Otherwise, what computer is the Assembly Code written for? Also you have to deal with the linker, etc. Lots of challenges (which original compilers had to deal with). What is "backend" in your statement? Is that the AST that a GNU code generator would use? That would be valid approach too.

0

u/DTCreeperMCL6 3h ago

Like llvm or QBE

1

u/konacurrents 1h ago

Thanks. I haven't dealt with LLVM or QBE (had to look it up). It seems these have similarities to the GNU code generator/generator. But the overall approach is you leverage those code generators. Writing in C (or say javascript) as the intermediate language is obviously a proven approach.

10

u/MCWizardYT 3h ago

The advantage is that C compilers exist already that have been optimized to death over decades. Take Clang/LLVM and GCC as examples.

If you can generate decent C code, these compilers will optimize the shit out of it for you.

You also get the bonus of automatically supporting multiple architectures instead of having to learn the syntax and optimization tricks of the assembly for every platform you want to support.

It's a bit similar to why someone would want to target something like CIL or JVM bytecode instead of writing their own virtual machine: most of the work has already been done, why reinvent the wheel?

3

u/Norphesius 2h ago

Cons: You are restricted to the C memory model, C's ABI, C's build quirks, and need to be vigilant about UB when generating code. 

It might not seem like that big a deal, after all you can approximate almost any feature you want in your langauge (and mask over C particulars) with enough generated C, but usually if you use C you'll want to make use of the C standard library. Now you have to make C interop a big part of your language, even if that doesn't really fit with the paradigm (functional, GC, memory safety, etc.). Even if you somehow reimplement glibc in your language natively, people will still want to interop with other C libraries, and would be confused if your lanagauge compiled to C but didn't have good interop with it.

And one very contextual downside: If you're building a language as a learning exercise, you may want to use it as an opportunity to learn assembly.

3

u/tabbekavalkade 3h ago

Compiling to C looks simpler to people who already know C, but don't know assembly. With all the UBs and odd behaviours of C, it is NOT simpler. If you know how you would like your language to work, and C just doesn't work that way, you have a problem.

Pros of compiling to C:

  • You don't have to write the optimizer.
  • You get some basic debug information from the C compiler.
  • Boehm GC gives you a GC for free.

Pros of compiling to assembly:

  • It's what you always wanted.
  • It's simpler, so mostly easier.
  • More uniform syntax.
  • It's more explicit, so you:
  • Get the exact rounding behaviour you want
  • Get the type conversion behaviour you want
  • Get the int wrapping behavour you want
  • Can make new constructs, like coroutines
  • Can maybe (?) label GC roots more easily, if your language has a GC
  • Can generate oddities like interleaved SSE/FPU instructions for boosting floating point computations in arrays in games.
  • Way faster compile times (from your language to binaries)
  • Inspectability: You know exactly what assembly your compiler generates, so when there is a bug, you can know where it is. C, with its permissive syntax, is an added layer of obfuscation, and disassembling what the C compiler wrote, is less helpful, and nothing like reading the assembly that you yourself generated.

1

u/DTCreeperMCL6 1h ago

Okay thanks, your comment is the only one Ive seen so far that says any of the advantages of using assembly. I know assembly but not too well and I only know one platform so I might try to learn llvm instead. I dont think I want my language to be a c wrapper.

1

u/WittyStick 39m ago edited 22m ago

GP missed out the disadvantages though - if you want your code to be efficient, you have to do instruction selection, instruction scheduling, register allocation, peephole optimization, and so forth.

These are each individually difficult problems, and they're often dependant not only on the ISA - but every CPU family may have different timings, OoO behavior, different cache behavior, branch prediction, and the list goes on. The timings are often not even published and need to be reverse engineered (eg, like uops.info, which are community efforts).

You can emit naive assembly without much trouble - but you are simply never going to match the efficiency of code produced by established C compilers (namely, GCC, Clang, ICC, MSVC, and a few other minor ones).

Moreover, these compilers will beat hand-written assembly 90% of the time because they are aware of these timings - you would have to look them up, because you certainly won't remember them all - and your finely optimized hand-written assembly is optimized only for one CPU family. The 10% where you can beat the compiler is usually some tightly optimized SIMD loop - where the compiler falls short because it isn't magic. For these cases, you can simply embed assembly in C to get the optimizations that the C compiler might miss.

There's a reason everyone just plugs in LLVM - they want their compiler to produce efficient code - but they don't have two decades or more that would be needed to even get close to parity with LLVM's optimizers - which are the culmination of hundreds of thousands of man hours of work, by experienced engineers, each specializing in particular parts.

Compiling to C is a cheap way to get these optimizations without having to learn the specifics of LLVM or GIMPLE. It's not the most efficient in terms of compile times because you have additional printing, parsing and the front-end optimizations done by Clang - whereas emitting LLVM IR involves fewer stages, or compiling directly through LLVM or GIMPLE's APIs is more efficient and avoids the round trip of printing/parsing.

7

u/mooglinux 3h ago

Compiling to C is a far simpler task than compiling to assembly, and lets you lean on the immense amount of human effort that has gone into making C compilers. The benefits are similar if you compiled to llvm bytecode, you get all of the optimizations and device support of llvm.

3

u/coderpants 3h ago

The main advantages to me are inspectability, interoperability and cross-platform capabilities.

ie it's harder to read assembly, it's more painful to drop out to native code, and you need to handle different assembler/calling semantics for different platforms.

The main disadvantages Is that likely you are buying into the C execution model - ie stack based rather than something a bit more exotic - if you try to escape then you likely lose the inspectability and interoperability.

3

u/SeaAnalyst8680 3h ago

Quite a lot has been written about how C accidentally became the de facto language of interfaces. E.g., if you're using Rust or C# and want to call out to some other component - even one written in, say, Python - the bindings are written in terms of C "things" (raw pointers, null terminated strings).

Obviously there are lots of other better ways to interface two specific ecosystems, but C is the lowest common denominator that is always an option (including when you don't know how the other component was created, e.g. a closed source library).

The answer to why languages often transpile to C is the same as to why C is used for interfaces, but if you research the interfaces aspect, you'll probably learn a lot of useful stuff along the way. Including why, if you want your programming language to ever be broadly adopted, you need to provide the functionality for it to make use of and behave as a C component.

And of course, if your language is built on C, it's straightforward to make it interact as though it were C.

3

u/GunpowderGuy 3h ago

Advantages :

-You can output c that will run on any compiler
-compiling to c makes interop with c libraries, easier

Disadvantages:

-C might not support features your language may need . Such tail call optimization.
-Hooking rts such as garbage collections might be more difficult than with a custom backend

2

u/an_unreal Lidl-Jai 3h ago

Compiling to C is just really straightforward. You don't need any third-party library (like LLVM) with a massive API and a steep learning curve, or dive too deep into the low-level details of calling conventions, register allocation, object files, etc for rolling your own machine code generator.

Additionally, compiling to C gives you full tooling support out-of-the-box (e.g. for debugging your code), and it's pretty easy to cross-compile and port to other platforms.

Finally, debugging your generated code is also a lot easier than some of the other solutions. You can always look at the C file that you generated and debug that. The C compiler will also catch some of the more obvious mistakes that you make.

2

u/Key_River7180 Nain. 3h ago

C is very portable and can do a lot of the heavy lifting for you. Cons: harder, much less flexibility

2

u/Ifeee001 3h ago

One con that I often see mentioned is that it'll be difficult to express certain things in C. But I personally wouldn't say it's difficult. It'll probably be more difficult in assembly.

An example is if expressions. C doesn't have that. But you could just desugar it into an uninitialised temp variable declaration and update the values at the appropriate place inside the if block. Every path inside the if block must assign to the temp variable. The else block will/must contain an initialization too so you don't get garbage memory.

E.g. let x = 23 if true else 24;

Hypothetical C:

int temp_if
if (true){temp_if = 23;}
else {temp_if = 24;}

const int mangled_x = tempif;

Ignore any errors. You could also take it a step further to "keep the scope clean" and take advantage of existing inclining optimization and make every if expression emit a function that'll return the result. That's probably over kill

Pretty much any common feature can be expressed in C if you're choosing it as your backend.

C also has a lot of hidden foot guns and undefined behavior.

2

u/vmcrash 3h ago

The advantage is that you can eliminate all the hard work done in the middle and backend. No need for lower-level IR, no need for register allocator, no need for creating optimal assembly code, no need for multiple backends for different targets.

1

u/mauriciocap 3h ago

Think of C as a virtual machine better than the one accepting e.g. x86 assembly. Notice x86 assembly can also be seen as a VM running over RISC assembly, etc.

Some advantages of generating C:

  • A LOT of toolchains for many many targets from emscripten to microcontrollers.
  • Easy to read, patch, customize redefining macros.
  • Most C compilers can do a lot of interesting optimizations.
  • DRY e.g. parameters, calls, structs, etc.

1

u/dreamingforward 3m ago

One advantage is that you can now compile to nearly any processor.

1

u/honey-pony 0m ago

For context, my project is a compiled game scripting language.

The main reason I am currently compiling to C for my it is because having someone else write the backend saves a lot of trouble. I'm able to build for Linux, Windows, and WASM without writing basically any target-specific code. I can also use tcc for faster debug builds.

But the reason to choose C here over LLVM is not actually for any of those reasons (and in fact, I think I will have to swap to LLVM due to some semantic requirements of my language that aren't expressible in C). Instead, my main reason to prefer C as a backend over LLVM is because it makes it trivial to call C functions. LLVM still does not have a built-in way to handle the C ABI, meaning that you have to do a bunch of target-specific and very error-prone work just to get function calls to work, which is super annoying.

0

u/phovos 3h ago edited 2h ago

What "C-like" ultimately portends is like Assembly + the "Abstract machine" + "Call by Reference/Call by value semantics".

In other words it is [pre-compiled] assembly but made with respect to each platforms abstract machine while dealing with any memory/bus hardware/bandwidth/etc. [2s compliment? etc.] (so writing the instructions per the platform, and changing the elements of the program that change with respect to those changes) changes.

(this is for C99 and onward, the 'abstract machine' was not fully parameterized in early years of C... actually I think its C89 and forward lol but I just always use C99)

edit: downvoter fight me you can't be more accurate or descriptive than the above without investing actual time or money in it (Oh, it must be; C89 fans not withstanding, probably just old-hats, any new young adherent will devote themselves to the C99 catechism, or newer).